-
Notifications
You must be signed in to change notification settings - Fork 186
/
cglmbuffer.cpp
1014 lines (837 loc) · 29 KB
/
cglmbuffer.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
//========= Copyright Valve Corporation, All rights reserved. ============//
// TOGL CODE LICENSE
//
// Copyright 2011-2014 Valve Corporation
// All Rights Reserved.
//
// 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.
//
// cglmbuffer.cpp
//
//===============================================================================
#include "togl/rendermechanism.h"
// memdbgon -must- be the last include file in a .cpp file.
#include "tier0/memdbgon.h"
// 7LS TODO : took out cmdline here
bool g_bUsePseudoBufs = false; //( Plat_GetCommandLineA() ) ? ( strstr( Plat_GetCommandLineA(), "-gl_enable_pseudobufs" ) != NULL ) : false;
bool g_bDisableStaticBuffer = false; //( Plat_GetCommandLineA() ) ? ( strstr( Plat_GetCommandLineA(), "-gl_disable_static_buffer" ) != NULL ) : false;
// http://www.opengl.org/registry/specs/ARB/vertex_buffer_object.txt
// http://www.opengl.org/registry/specs/ARB/pixel_buffer_object.txt
// gl_bufmode: zero means we mark all vertex/index buffers static
// non zero means buffers are initially marked static..
// ->but can shift to dynamic upon first 'discard' (orphaning)
// #define REPORT_LOCK_TIME 0
ConVar gl_bufmode( "gl_bufmode", "1" );
char ALIGN16 CGLMBuffer::m_StaticBuffers[ GL_MAX_STATIC_BUFFERS ][ GL_STATIC_BUFFER_SIZE ] ALIGN16_POST;
bool CGLMBuffer::m_bStaticBufferUsed[ GL_MAX_STATIC_BUFFERS ];
extern bool g_bNullD3DDevice;
#if GL_ENABLE_INDEX_VERIFICATION
CGLMBufferSpanManager::CGLMBufferSpanManager() :
m_pCtx( NULL ),
m_nBufType( kGLMVertexBuffer ),
m_nBufSize( 0 ),
m_bDynamic( false ),
m_nSpanEndMax( -1 ),
m_nNumAllocatedBufs( 0 ),
m_nTotalBytesAllocated( 0 )
{
}
CGLMBufferSpanManager::~CGLMBufferSpanManager()
{
Deinit();
}
void CGLMBufferSpanManager::Init( GLMContext *pContext, EGLMBufferType nBufType, uint nInitialCapacity, uint nBufSize, bool bDynamic )
{
Assert( ( nBufType == kGLMIndexBuffer ) || ( nBufType == kGLMVertexBuffer ) );
m_pCtx = pContext;
m_nBufType = nBufType;
m_nBufSize = nBufSize;
m_bDynamic = bDynamic;
m_ActiveSpans.EnsureCapacity( nInitialCapacity );
m_DeletedSpans.EnsureCapacity( nInitialCapacity );
m_nSpanEndMax = -1;
m_nNumAllocatedBufs = 0;
m_nTotalBytesAllocated = 0;
}
bool CGLMBufferSpanManager::AllocDynamicBuf( uint nSize, GLDynamicBuf_t &buf )
{
buf.m_nGLType = GetGLBufType();
buf.m_nActualBufSize = nSize;
buf.m_nHandle = 0;
buf.m_nSize = nSize;
m_nNumAllocatedBufs++;
m_nTotalBytesAllocated += buf.m_nActualBufSize;
return true;
}
void CGLMBufferSpanManager::ReleaseDynamicBuf( GLDynamicBuf_t &buf )
{
Assert( m_nNumAllocatedBufs > 0 );
m_nNumAllocatedBufs--;
Assert( m_nTotalBytesAllocated >= (int)buf.m_nActualBufSize );
m_nTotalBytesAllocated -= buf.m_nActualBufSize;
}
void CGLMBufferSpanManager::Deinit()
{
if ( !m_pCtx )
return;
for ( int i = 0; i < m_ActiveSpans.Count(); i++ )
{
if ( m_ActiveSpans[i].m_bOriginalAlloc )
ReleaseDynamicBuf( m_ActiveSpans[i].m_buf );
}
m_ActiveSpans.SetCountNonDestructively( 0 );
for ( int i = 0; i < m_DeletedSpans.Count(); i++ )
ReleaseDynamicBuf( m_DeletedSpans[i].m_buf );
m_DeletedSpans.SetCountNonDestructively( 0 );
m_pCtx->BindGLBufferToCtx( GetGLBufType(), NULL, true );
m_nSpanEndMax = -1;
m_pCtx = NULL;
Assert( !m_nNumAllocatedBufs );
Assert( !m_nTotalBytesAllocated );
}
void CGLMBufferSpanManager::DiscardAllSpans()
{
for ( int i = 0; i < m_ActiveSpans.Count(); i++ )
{
if ( m_ActiveSpans[i].m_bOriginalAlloc )
ReleaseDynamicBuf( m_ActiveSpans[i].m_buf );
}
m_ActiveSpans.SetCountNonDestructively( 0 );
for ( int i = 0; i < m_DeletedSpans.Count(); i++ )
ReleaseDynamicBuf( m_DeletedSpans[i].m_buf );
m_DeletedSpans.SetCountNonDestructively( 0 );
m_nSpanEndMax = -1;
Assert( !m_nNumAllocatedBufs );
Assert( !m_nTotalBytesAllocated );
}
// TODO: Add logic to detect incorrect usage of bNoOverwrite.
CGLMBufferSpanManager::ActiveSpan_t *CGLMBufferSpanManager::AddSpan( uint nOffset, uint nMaxSize, uint nActualSize, bool bDiscard, bool bNoOverwrite )
{
(void)bDiscard;
(void)bNoOverwrite;
const uint nStart = nOffset;
const uint nSize = nActualSize;
const uint nEnd = nStart + nSize;
GLDynamicBuf_t newDynamicBuf;
if ( !AllocDynamicBuf( nSize, newDynamicBuf ) )
{
DXABSTRACT_BREAK_ON_ERROR();
return NULL;
}
if ( (int)nStart < m_nSpanEndMax )
{
// Lock region potentially overlaps another previously locked region (since the last discard) - this is a very rarely (if ever) taken path in Source1 games.
int i = 0;
while ( i < m_ActiveSpans.Count() )
{
ActiveSpan_t &existingSpan = m_ActiveSpans[i];
if ( ( nEnd <= existingSpan.m_nStart ) || ( nStart >= existingSpan.m_nEnd ) )
{
i++;
continue;
}
Warning( "GL performance warning: AddSpan() at offset %u max size %u actual size %u, on a %s %s buffer of total size %u, overwrites an existing active lock span at offset %u size %u!\n",
nOffset, nMaxSize, nActualSize,
m_bDynamic ? "dynamic" : "static", ( m_nBufType == kGLMVertexBuffer ) ? "vertex" : "index", m_nBufSize,
existingSpan.m_nStart, existingSpan.m_nEnd - existingSpan.m_nStart );
if ( ( nStart <= existingSpan.m_nStart ) && ( nEnd >= existingSpan.m_nEnd ) )
{
if ( existingSpan.m_bOriginalAlloc )
{
// New span totally covers existing span
// Can't immediately delete the span's buffer because it could be referred to by another (child) span.
m_DeletedSpans.AddToTail( existingSpan );
}
// Delete span
m_ActiveSpans[i] = m_ActiveSpans[ m_ActiveSpans.Count() - 1 ];
m_ActiveSpans.SetCountNonDestructively( m_ActiveSpans.Count() - 1 );
continue;
}
// New span does NOT fully cover the existing span (partial overlap)
if ( nStart < existingSpan.m_nStart )
{
// New span starts before existing span, but ends somewhere inside, so shrink it (start moves "right")
existingSpan.m_nStart = nEnd;
}
else if ( nEnd > existingSpan.m_nEnd )
{
// New span ends after existing span, but starts somewhere inside (end moves "left")
existingSpan.m_nEnd = nStart;
}
else //if ( ( nStart >= existingSpan.m_nStart ) && ( nEnd <= existingSpan.m_nEnd ) )
{
// New span lies inside of existing span
if ( nStart == existingSpan.m_nStart )
{
// New span begins inside the existing span (start moves "right")
existingSpan.m_nStart = nEnd;
}
else
{
if ( nEnd < existingSpan.m_nEnd )
{
// New span is completely inside existing span
m_ActiveSpans.AddToTail( ActiveSpan_t( nEnd, existingSpan.m_nEnd, existingSpan.m_buf, false ) );
}
existingSpan.m_nEnd = nStart;
}
}
Assert( existingSpan.m_nStart < existingSpan.m_nEnd );
i++;
}
}
newDynamicBuf.m_nLockOffset = nStart;
newDynamicBuf.m_nLockSize = nSize;
m_ActiveSpans.AddToTail( ActiveSpan_t( nStart, nEnd, newDynamicBuf, true ) );
m_nSpanEndMax = MAX( m_nSpanEndMax, (int)nEnd );
return &m_ActiveSpans.Tail();
}
bool CGLMBufferSpanManager::IsValid( uint nOffset, uint nSize ) const
{
const uint nEnd = nOffset + nSize;
int nTotalBytesRemaining = nSize;
for ( int i = m_ActiveSpans.Count() - 1; i >= 0; --i )
{
const ActiveSpan_t &span = m_ActiveSpans[i];
if ( span.m_nEnd <= nOffset )
continue;
if ( span.m_nStart >= nEnd )
continue;
uint nIntersectStart = MAX( span.m_nStart, nOffset );
uint nIntersectEnd = MIN( span.m_nEnd, nEnd );
Assert( nIntersectStart <= nIntersectEnd );
nTotalBytesRemaining -= ( nIntersectEnd - nIntersectStart );
Assert( nTotalBytesRemaining >= 0 );
if ( nTotalBytesRemaining <= 0 )
break;
}
return nTotalBytesRemaining == 0;
}
#endif // GL_ENABLE_INDEX_VERIFICATION
// glBufferSubData() with a max size limit, to work around NVidia's threaded driver limits (anything > than roughly 256KB triggers a sync with the server thread).
void glBufferSubDataMaxSize( GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid *data, uint nMaxSizePerCall )
{
#if TOGL_SUPPORT_NULL_DEVICE
if ( g_bNullD3DDevice ) return;
#endif
uint nBytesLeft = size;
uint nOfs = 0;
while ( nBytesLeft )
{
uint nBytesToCopy = MIN( nMaxSizePerCall, nBytesLeft );
gGL->glBufferSubData( target, offset + nOfs, nBytesToCopy, static_cast<const unsigned char *>( data ) + nOfs );
nBytesLeft -= nBytesToCopy;
nOfs += nBytesToCopy;
}
}
CGLMBuffer::CGLMBuffer( GLMContext *pCtx, EGLMBufferType type, uint size, uint options )
{
m_pCtx = pCtx;
m_type = type;
m_bDynamic = ( options & GLMBufferOptionDynamic ) != 0;
switch ( m_type )
{
case kGLMVertexBuffer: m_buffGLTarget = GL_ARRAY_BUFFER_ARB; break;
case kGLMIndexBuffer: m_buffGLTarget = GL_ELEMENT_ARRAY_BUFFER_ARB; break;
case kGLMUniformBuffer: m_buffGLTarget = GL_UNIFORM_BUFFER_EXT; break;
case kGLMPixelBuffer: m_buffGLTarget = GL_PIXEL_UNPACK_BUFFER_ARB; break;
default: Assert(!"Unknown buffer type" ); DXABSTRACT_BREAK_ON_ERROR();
}
m_nSize = size;
m_nActualSize = size;
m_bMapped = false;
m_pLastMappedAddress = NULL;
m_pStaticBuffer = NULL;
m_nPinnedMemoryOfs = -1;
m_bEnableAsyncMap = false;
m_bEnableExplicitFlush = false;
m_dirtyMinOffset = m_dirtyMaxOffset = 0; // adjust/grow on lock, clear on unlock
m_pCtx->CheckCurrent();
m_nRevision = rand();
m_pPseudoBuf = NULL;
m_pActualPseudoBuf = NULL;
m_bPseudo = false;
#if GL_ENABLE_UNLOCK_BUFFER_OVERWRITE_DETECTION
m_bPseudo = true;
#endif
#if GL_ENABLE_INDEX_VERIFICATION
m_BufferSpanManager.Init( m_pCtx, m_type, 512, m_nSize, m_bDynamic );
if ( m_type == kGLMIndexBuffer )
m_bPseudo = true;
#endif
if ( g_bUsePseudoBufs && m_bDynamic )
{
m_bPseudo = true;
}
if ( m_bPseudo )
{
m_nHandle = 0;
#if GL_ENABLE_UNLOCK_BUFFER_OVERWRITE_DETECTION
m_nDirtyRangeStart = 0xFFFFFFFF;
m_nDirtyRangeEnd = 0;
m_nActualSize = ALIGN_VALUE( ( m_nSize + sizeof( uint32 ) ), 4096 );
m_pPseudoBuf = m_pActualPseudoBuf = (char *)VirtualAlloc( NULL, m_nActualSize, MEM_COMMIT, PAGE_READWRITE );
if ( !m_pPseudoBuf )
{
Error( "VirtualAlloc() failed!\n" );
}
for ( uint i = 0; i < m_nActualSize / sizeof( uint32 ); i++ )
{
reinterpret_cast< uint32 * >( m_pPseudoBuf )[i] = 0xDEADBEEF;
}
DWORD nOldProtect;
BOOL bResult = VirtualProtect( m_pActualPseudoBuf, m_nActualSize, PAGE_READONLY, &nOldProtect );
if ( !bResult )
{
Error( "VirtualProtect() failed!\n" );
}
#else
m_nActualSize = size + 15;
m_pActualPseudoBuf = (char*)malloc( m_nActualSize );
m_pPseudoBuf = (char*)(((intp)m_pActualPseudoBuf + 15) & ~15);
#endif
m_pCtx->BindBufferToCtx( m_type, NULL ); // exit with no buffer bound
}
else
{
gGL->glGenBuffersARB( 1, &m_nHandle );
m_pCtx->BindBufferToCtx( m_type, this ); // causes glBindBufferARB
// buffers start out static, but if they get orphaned and gl_bufmode is non zero,
// then they will get flipped to dynamic.
GLenum hint = GL_STATIC_DRAW_ARB;
switch (m_type)
{
case kGLMVertexBuffer: hint = m_bDynamic ? GL_DYNAMIC_DRAW_ARB : GL_STATIC_DRAW_ARB; break;
case kGLMIndexBuffer: hint = m_bDynamic ? GL_DYNAMIC_DRAW_ARB : GL_STATIC_DRAW_ARB; break;
case kGLMUniformBuffer: hint = GL_DYNAMIC_DRAW_ARB; break;
case kGLMPixelBuffer: hint = m_bDynamic ? GL_DYNAMIC_DRAW_ARB : GL_STATIC_DRAW_ARB; break;
default: Assert(!"Unknown buffer type" ); DXABSTRACT_BREAK_ON_ERROR();
}
gGL->glBufferDataARB( m_buffGLTarget, m_nSize, (const GLvoid*)NULL, hint ); // may ultimately need more hints to set the usage correctly (esp for streaming)
SetModes( false, true, true );
m_pCtx->BindBufferToCtx( m_type, NULL ); // unbind me
}
}
CGLMBuffer::~CGLMBuffer( )
{
m_pCtx->CheckCurrent();
if ( m_bPseudo )
{
#if GL_ENABLE_UNLOCK_BUFFER_OVERWRITE_DETECTION
BOOL bResult = VirtualFree( m_pActualPseudoBuf, 0, MEM_RELEASE );
if ( !bResult )
{
Error( "VirtualFree() failed!\n" );
}
#else
free( m_pActualPseudoBuf );
#endif
m_pActualPseudoBuf = NULL;
m_pPseudoBuf = NULL;
}
else
{
gGL->glDeleteBuffersARB( 1, &m_nHandle );
}
m_pCtx = NULL;
m_nHandle = 0;
m_pLastMappedAddress = NULL;
#if GL_ENABLE_INDEX_VERIFICATION
m_BufferSpanManager.Deinit();
#endif
}
void CGLMBuffer::SetModes( bool bAsyncMap, bool bExplicitFlush, bool bForce )
{
// assumes buffer is bound. called by constructor and by Lock.
if ( m_bPseudo )
{
// ignore it...
}
else
{
if ( bForce || ( m_bEnableAsyncMap != bAsyncMap ) )
{
// note the sense of the parameter, it's TRUE if you *want* serialization, so for async you turn it to false.
if ( ( gGL->m_bHave_GL_APPLE_flush_buffer_range ) && ( !gGL->m_bHave_GL_ARB_map_buffer_range ) )
{
gGL->glBufferParameteriAPPLE( m_buffGLTarget, GL_BUFFER_SERIALIZED_MODIFY_APPLE, bAsyncMap == false );
}
m_bEnableAsyncMap = bAsyncMap;
}
if ( bForce || ( m_bEnableExplicitFlush != bExplicitFlush ) )
{
// Note that the GL_ARB_map_buffer_range path handles this in the glMapBufferRange() call in Lock().
// note the sense of the parameter, it's TRUE if you *want* auto-flush-on-unmap, so for explicit-flush, you turn it to false.
if ( ( gGL->m_bHave_GL_APPLE_flush_buffer_range ) && ( !gGL->m_bHave_GL_ARB_map_buffer_range ) )
{
gGL->glBufferParameteriAPPLE( m_buffGLTarget, GL_BUFFER_FLUSHING_UNMAP_APPLE, bExplicitFlush == false );
}
m_bEnableExplicitFlush = bExplicitFlush;
}
}
}
#if GL_ENABLE_INDEX_VERIFICATION
bool CGLMBuffer::IsSpanValid( uint nOffset, uint nSize ) const
{
return m_BufferSpanManager.IsValid( nOffset, nSize );
}
#endif
void CGLMBuffer::FlushRange( uint offset, uint size )
{
if ( m_pStaticBuffer )
{
}
else if ( m_bPseudo )
{
// nothing to do
}
else
{
#ifdef REPORT_LOCK_TIME
double flStart = Plat_FloatTime();
#endif
// assumes buffer is bound.
if ( gGL->m_bHave_GL_ARB_map_buffer_range )
{
gGL->glFlushMappedBufferRange( m_buffGLTarget, (GLintptr)( offset - m_dirtyMinOffset ), (GLsizeiptr)size );
}
else if ( gGL->m_bHave_GL_APPLE_flush_buffer_range )
{
gGL->glFlushMappedBufferRangeAPPLE( m_buffGLTarget, (GLintptr)offset, (GLsizeiptr)size );
}
#ifdef REPORT_LOCK_TIME
double flEnd = Plat_FloatTime();
if ( flEnd - flStart > 5.0 / 1000.0 )
{
int nDelta = ( int )( ( flEnd - flStart ) * 1000 );
if ( nDelta > 2 )
{
Msg( "**** " );
}
Msg( "glFlushMappedBufferRange Time %d: ( Name=%d BufSize=%d ) Target=%p Offset=%d FlushSize=%d\n", nDelta, m_nHandle, m_nSize, m_buffGLTarget, offset - m_dirtyMinOffset, size );
}
#endif
// If you don't have any extension support here, you'll flush the whole buffer on unmap. Performance loss, but it's still safe and correct.
}
}
void CGLMBuffer::Lock( GLMBuffLockParams *pParams, char **pAddressOut )
{
#if GL_TELEMETRY_GPU_ZONES
CScopedGLMPIXEvent glmPIXEvent( "CGLMBuffer::Lock" );
g_TelemetryGPUStats.m_nTotalBufferLocksAndUnlocks++;
#endif
char *resultPtr = NULL;
if ( m_bMapped )
{
DXABSTRACT_BREAK_ON_ERROR();
return;
}
m_pCtx->CheckCurrent();
Assert( pParams->m_nSize );
m_LockParams = *pParams;
if ( pParams->m_nOffset >= m_nSize )
{
DXABSTRACT_BREAK_ON_ERROR();
return;
}
if ( ( pParams->m_nOffset + pParams->m_nSize ) > m_nSize)
{
DXABSTRACT_BREAK_ON_ERROR();
return;
}
#if GL_ENABLE_INDEX_VERIFICATION
if ( pParams->m_bDiscard )
{
m_BufferSpanManager.DiscardAllSpans();
}
#endif
m_pStaticBuffer = NULL;
if ( m_bPseudo )
{
if ( pParams->m_bDiscard )
{
m_nRevision++;
}
// async map modes are a no-op
// calc lock address
resultPtr = m_pPseudoBuf + pParams->m_nOffset;
#if GL_ENABLE_UNLOCK_BUFFER_OVERWRITE_DETECTION
BOOL bResult;
DWORD nOldProtect;
if ( pParams->m_bDiscard )
{
bResult = VirtualProtect( m_pActualPseudoBuf, m_nSize, PAGE_READWRITE, &nOldProtect );
if ( !bResult )
{
Error( "VirtualProtect() failed!\n" );
}
m_nDirtyRangeStart = 0xFFFFFFFF;
m_nDirtyRangeEnd = 0;
for ( uint i = 0; i < m_nSize / sizeof( uint32 ); i++ )
{
reinterpret_cast< uint32 * >( m_pPseudoBuf )[i] = 0xDEADBEEF;
}
bResult = VirtualProtect( m_pActualPseudoBuf, m_nSize, PAGE_READONLY, &nOldProtect );
if ( !bResult )
{
Error( "VirtualProtect() failed!\n" );
}
}
uint nProtectOfs = m_LockParams.m_nOffset & 4095;
uint nProtectEnd = ( m_LockParams.m_nOffset + m_LockParams.m_nSize + 4095 ) & ~4095;
uint nProtectSize = nProtectEnd - nProtectOfs;
bResult = VirtualProtect( m_pActualPseudoBuf + nProtectOfs, nProtectSize, PAGE_READWRITE, &nOldProtect );
if ( !bResult )
{
Error( "VirtualProtect() failed!\n" );
}
#endif
}
else if ( m_bDynamic && gGL->m_bHave_GL_AMD_pinned_memory && ( m_pCtx->GetCurPinnedMemoryBuffer()->GetBytesRemaining() >= pParams->m_nSize ) )
{
if ( pParams->m_bDiscard )
{
m_nRevision++;
}
m_dirtyMinOffset = pParams->m_nOffset;
m_dirtyMaxOffset = pParams->m_nOffset + pParams->m_nSize;
CPinnedMemoryBuffer *pTempBuffer = m_pCtx->GetCurPinnedMemoryBuffer();
m_nPinnedMemoryOfs = pTempBuffer->GetOfs();
resultPtr = static_cast<char*>( pTempBuffer->GetPtr() ) + m_nPinnedMemoryOfs;
pTempBuffer->Append( pParams->m_nSize );
}
else if ( !g_bDisableStaticBuffer && ( pParams->m_bDiscard || pParams->m_bNoOverwrite ) && ( pParams->m_nSize <= GL_STATIC_BUFFER_SIZE ) )
{
#if TOGL_SUPPORT_NULL_DEVICE
if ( !g_bNullD3DDevice )
#endif
{
if ( pParams->m_bDiscard )
{
m_pCtx->BindBufferToCtx( m_type, this );
// observe gl_bufmode on any orphan event.
// if orphaned and bufmode is nonzero, flip it to dynamic.
GLenum hint = gl_bufmode.GetInt() ? GL_DYNAMIC_DRAW_ARB : GL_STATIC_DRAW_ARB;
gGL->glBufferDataARB( m_buffGLTarget, m_nSize, (const GLvoid*)NULL, hint );
m_nRevision++; // revision grows on orphan event
}
}
m_dirtyMinOffset = pParams->m_nOffset;
m_dirtyMaxOffset = pParams->m_nOffset + pParams->m_nSize;
switch ( m_type )
{
case kGLMVertexBuffer:
{
m_pStaticBuffer = m_StaticBuffers[ 0 ];
break;
}
case kGLMIndexBuffer:
{
m_pStaticBuffer = m_StaticBuffers[ 1 ];
break;
}
default:
{
DXABSTRACT_BREAK_ON_ERROR();
return;
}
}
resultPtr = m_pStaticBuffer;
}
else
{
// bind (yes, even for pseudo - this binds name 0)
m_pCtx->BindBufferToCtx( m_type, this );
// perform discard if requested
if ( pParams->m_bDiscard )
{
// observe gl_bufmode on any orphan event.
// if orphaned and bufmode is nonzero, flip it to dynamic.
// We always want to call glBufferData( ..., NULL ) on discards, even though we're using the GL_MAP_INVALIDATE_BUFFER_BIT flag, because this flag is actually only a hint according to AMD.
GLenum hint = gl_bufmode.GetInt() ? GL_DYNAMIC_DRAW_ARB : GL_STATIC_DRAW_ARB;
gGL->glBufferDataARB( m_buffGLTarget, m_nSize, (const GLvoid*)NULL, hint );
m_nRevision++; // revision grows on orphan event
}
// adjust async map option appropriately, leave explicit flush unchanged
SetModes( pParams->m_bNoOverwrite, m_bEnableExplicitFlush );
// map
char *mapPtr;
if ( gGL->m_bHave_GL_ARB_map_buffer_range )
{
// m_bEnableAsyncMap is actually pParams->m_bNoOverwrite
GLbitfield parms = GL_MAP_WRITE_BIT | ( m_bEnableAsyncMap ? GL_MAP_UNSYNCHRONIZED_BIT : 0 ) | ( pParams->m_bDiscard ? GL_MAP_INVALIDATE_BUFFER_BIT : 0 ) | ( m_bEnableExplicitFlush ? GL_MAP_FLUSH_EXPLICIT_BIT : 0 );
#ifdef REPORT_LOCK_TIME
double flStart = Plat_FloatTime();
#endif
mapPtr = (char*)gGL->glMapBufferRange( m_buffGLTarget, pParams->m_nOffset, pParams->m_nSize, parms);
#ifdef REPORT_LOCK_TIME
double flEnd = Plat_FloatTime();
if ( flEnd - flStart > 5.0 / 1000.0 )
{
int nDelta = ( int )( ( flEnd - flStart ) * 1000 );
if ( nDelta > 2 )
{
Msg( "**** " );
}
Msg( "glMapBufferRange Time=%d: ( Name=%d BufSize=%d ) Target=%p Offset=%d LockSize=%d ", nDelta, m_nHandle, m_nSize, m_buffGLTarget, pParams->m_nOffset, pParams->m_nSize );
if ( parms & GL_MAP_WRITE_BIT )
{
Msg( "GL_MAP_WRITE_BIT ");
}
if ( parms & GL_MAP_UNSYNCHRONIZED_BIT )
{
Msg( "GL_MAP_UNSYNCHRONIZED_BIT ");
}
if ( parms & GL_MAP_INVALIDATE_BUFFER_BIT )
{
Msg( "GL_MAP_INVALIDATE_BUFFER_BIT ");
}
if ( parms & GL_MAP_INVALIDATE_RANGE_BIT )
{
Msg( "GL_MAP_INVALIDATE_RANGE_BIT ");
}
if ( parms & GL_MAP_FLUSH_EXPLICIT_BIT )
{
Msg( "GL_MAP_FLUSH_EXPLICIT_BIT ");
}
Msg( "\n" );
}
#endif
}
else
{
mapPtr = (char*)gGL->glMapBufferARB( m_buffGLTarget, GL_WRITE_ONLY_ARB );
}
Assert( mapPtr );
// calculate offset location
resultPtr = mapPtr;
if ( !gGL->m_bHave_GL_ARB_map_buffer_range )
{
resultPtr += pParams->m_nOffset;
}
// set range
m_dirtyMinOffset = pParams->m_nOffset;
m_dirtyMaxOffset = pParams->m_nOffset + pParams->m_nSize;
}
m_bMapped = true;
m_pLastMappedAddress = (float*)resultPtr;
*pAddressOut = resultPtr;
}
void CGLMBuffer::Unlock( int nActualSize, const void *pActualData )
{
#if GL_TELEMETRY_GPU_ZONES
CScopedGLMPIXEvent glmPIXEvent( "CGLMBuffer::Unlock" );
g_TelemetryGPUStats.m_nTotalBufferLocksAndUnlocks++;
#endif
m_pCtx->CheckCurrent();
if ( !m_bMapped )
{
DXABSTRACT_BREAK_ON_ERROR();
return;
}
if ( nActualSize < 0 )
{
nActualSize = m_LockParams.m_nSize;
}
if ( nActualSize > (int)m_LockParams.m_nSize )
{
DXABSTRACT_BREAK_ON_ERROR();
return;
}
#if GL_ENABLE_UNLOCK_BUFFER_OVERWRITE_DETECTION
if ( m_bPseudo )
{
// Check guard DWORD to detect buffer overruns (but are still within the last 4KB page so they don't get caught via pagefaults)
if ( *reinterpret_cast< const uint32 * >( m_pPseudoBuf + m_nSize ) != 0xDEADBEEF )
{
// If this fires the client app has overwritten the guard DWORD beyond the end of the buffer.
DXABSTRACT_BREAK_ON_ERROR();
}
static const uint s_nInitialValues[4] = { 0xEF, 0xBE, 0xAD, 0xDE };
int nActualModifiedStart, nActualModifiedEnd;
for ( nActualModifiedStart = 0; nActualModifiedStart < (int)m_LockParams.m_nSize; ++nActualModifiedStart )
if ( reinterpret_cast< const uint8 * >( m_pLastMappedAddress )[nActualModifiedStart] != s_nInitialValues[ ( m_LockParams.m_nOffset + nActualModifiedStart ) & 3 ] )
break;
for ( nActualModifiedEnd = m_LockParams.m_nSize - 1; nActualModifiedEnd > nActualModifiedStart; --nActualModifiedEnd )
if ( reinterpret_cast< const uint8 * >( m_pLastMappedAddress )[nActualModifiedEnd] != s_nInitialValues[ ( m_LockParams.m_nOffset + nActualModifiedEnd ) & 3 ] )
break;
int nNumActualBytesModified = 0;
if ( nActualModifiedEnd >= nActualModifiedStart )
{
// The modified check is conservative (i.e. it should always err on the side of detecting <= actual bytes than where actually modified, never more).
// We primarily care about the case where the user lies about the actual # of modified bytes, which can lead to difficult to debug/inconsistent problems with some drivers.
// Round up/down the modified range, because the user's data may alias with the initial buffer values (0xDEADBEEF) so we may miss some bytes that where written.
if ( m_type == kGLMIndexBuffer )
{
nActualModifiedStart &= ~1;
nActualModifiedEnd = MIN( (int)m_LockParams.m_nSize, ( ( nActualModifiedEnd + 1 ) + 1 ) & ~1 ) - 1;
}
else
{
nActualModifiedStart &= ~3;
nActualModifiedEnd = MIN( (int)m_LockParams.m_nSize, ( ( nActualModifiedEnd + 1 ) + 3 ) & ~3 ) - 1;
}
nNumActualBytesModified = nActualModifiedEnd + 1;
if ( nActualSize < nNumActualBytesModified )
{
// The caller may be lying about the # of actually modified bytes in this lock.
// Has this lock region been previously locked? If so, it may have been previously overwritten before. Otherwise, the region had to be the 0xDEADBEEF fill DWORD at lock time.
if ( ( m_nDirtyRangeStart > m_nDirtyRangeEnd ) ||
( m_LockParams.m_nOffset > m_nDirtyRangeEnd ) || ( ( m_LockParams.m_nOffset + m_LockParams.m_nSize ) <= m_nDirtyRangeStart ) )
{
// If this fires the client has lied about the actual # of bytes they've modified in the buffer - this will cause unreliable rendering on AMD drivers (because AMD actually pays attention to the actual # of flushed bytes).
DXABSTRACT_BREAK_ON_ERROR();
}
}
m_nDirtyRangeStart = MIN( m_nDirtyRangeStart, m_LockParams.m_nOffset + nActualModifiedStart );
m_nDirtyRangeEnd = MAX( m_nDirtyRangeEnd, m_LockParams.m_nOffset + nActualModifiedEnd );
}
#if GL_ENABLE_INDEX_VERIFICATION
if ( nActualModifiedEnd >= nActualModifiedStart )
{
int n = nActualModifiedEnd + 1;
if ( n != nActualSize )
{
// The actual detected modified size is < than the reported size, which is common because the last few DWORD's of the vertex format may not actually be used/written (or read by the vertex shader). So just fudge it so the batch consumption checks work.
if ( ( (int)nActualSize - n ) <= 32 )
{
n = nActualSize;
}
}
m_BufferSpanManager.AddSpan( m_LockParams.m_nOffset + nActualModifiedStart, m_LockParams.m_nSize, n - nActualModifiedStart, m_LockParams.m_bDiscard, m_LockParams.m_bNoOverwrite );
}
#endif
}
#elif GL_ENABLE_INDEX_VERIFICATION
if ( nActualSize > 0 )
{
m_BufferSpanManager.AddSpan( m_LockParams.m_nOffset, m_LockParams.m_nSize, nActualSize, m_LockParams.m_bDiscard, m_LockParams.m_bNoOverwrite );
}
#endif
#if GL_BATCH_PERF_ANALYSIS
if ( m_type == kGLMIndexBuffer )
g_nTotalIBLockBytes += nActualSize;
else if ( m_type == kGLMVertexBuffer )
g_nTotalVBLockBytes += nActualSize;
#endif
if ( m_nPinnedMemoryOfs >= 0 )
{
#if TOGL_SUPPORT_NULL_DEVICE
if ( !g_bNullD3DDevice )
{
#endif
if ( nActualSize )
{
m_pCtx->BindBufferToCtx( m_type, this );
gGL->glCopyBufferSubData(
GL_EXTERNAL_VIRTUAL_MEMORY_BUFFER_AMD,
m_buffGLTarget,
m_nPinnedMemoryOfs,
m_dirtyMinOffset,
nActualSize );
}
#if TOGL_SUPPORT_NULL_DEVICE
}
#endif
m_nPinnedMemoryOfs = -1;
}
else if ( m_pStaticBuffer )
{
#if TOGL_SUPPORT_NULL_DEVICE
if ( !g_bNullD3DDevice )
#endif
{
if ( nActualSize )
{
tmZone( TELEMETRY_LEVEL2, TMZF_NONE, "UnlockSubData" );
#ifdef REPORT_LOCK_TIME
double flStart = Plat_FloatTime();
#endif
m_pCtx->BindBufferToCtx( m_type, this );
Assert( nActualSize <= (int)( m_dirtyMaxOffset - m_dirtyMinOffset ) );
glBufferSubDataMaxSize( m_buffGLTarget, m_dirtyMinOffset, nActualSize, pActualData ? pActualData : m_pStaticBuffer );
#ifdef REPORT_LOCK_TIME
double flEnd = Plat_FloatTime();
if ( flEnd - flStart > 5.0 / 1000.0 )
{
int nDelta = ( int )( ( flEnd - flStart ) * 1000 );
if ( nDelta > 2 )
{
Msg( "**** " );
}
// Msg( "glBufferSubData Time=%d: ( Name=%d BufSize=%d ) Target=%p Offset=%d Size=%d\n", nDelta, m_nHandle, m_nSize, m_buffGLTarget, m_dirtyMinOffset, m_dirtyMaxOffset - m_dirtyMinOffset );
}
#endif
}
}
m_pStaticBuffer = NULL;
}
else if ( m_bPseudo )
{
if ( pActualData )
{
memcpy( m_pLastMappedAddress, pActualData, nActualSize );
}
#if GL_ENABLE_UNLOCK_BUFFER_OVERWRITE_DETECTION
uint nProtectOfs = m_LockParams.m_nOffset & 4095;
uint nProtectEnd = ( m_LockParams.m_nOffset + m_LockParams.m_nSize + 4095 ) & ~4095;
uint nProtectSize = nProtectEnd - nProtectOfs;
DWORD nOldProtect;
BOOL bResult = VirtualProtect( m_pActualPseudoBuf + nProtectOfs, nProtectSize, PAGE_READONLY, &nOldProtect );
if ( !bResult )
{
Error( "VirtualProtect() failed!\n" );
}
#endif
}
else
{
tmZone( TELEMETRY_LEVEL2, TMZF_NONE, "UnlockUnmap" );
if ( pActualData )
{
memcpy( m_pLastMappedAddress, pActualData, nActualSize );
}
m_pCtx->BindBufferToCtx( m_type, this );
Assert( nActualSize <= (int)( m_dirtyMaxOffset - m_dirtyMinOffset ) );
// time to do explicit flush (currently m_bEnableExplicitFlush is always true)
if ( m_bEnableExplicitFlush )
{
FlushRange( m_dirtyMinOffset, nActualSize );
}
// clear dirty range no matter what
m_dirtyMinOffset = m_dirtyMaxOffset = 0; // adjust/grow on lock, clear on unlock
#ifdef REPORT_LOCK_TIME
double flStart = Plat_FloatTime();
#endif
gGL->glUnmapBuffer( m_buffGLTarget );
#ifdef REPORT_LOCK_TIME
double flEnd = Plat_FloatTime();