-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathApus.Engine.OpenGL.pas
More file actions
1367 lines (1267 loc) · 41.6 KB
/
Apus.Engine.OpenGL.pas
File metadata and controls
1367 lines (1267 loc) · 41.6 KB
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
// OpenGL wrapper for the engine
//
// Copyright (C) 2020 Ivan Polyacov, Apus Software (ivan@apus-software.com)
// This file is licensed under the terms of BSD-3 license (see license.txt)
// This file is a part of the Apus Game Engine (http://apus-software.com/engine/)
{$I defines.inc}
unit Apus.Engine.OpenGL;
interface
uses Apus.Core, Apus.Engine.API, Apus.Images;
type
TOpenGLContextProfile=(oglpAny,
oglpCompatibility,
oglpCore);
TOpenGLContextDesc=record
// request
minMajor:byte;
minMinor:byte;
profile:TOpenGLContextProfile;
debugContext:boolean;
forwardCompatible:boolean;
preferHighest:boolean;
// actual
actualMajor:byte;
actualMinor:byte;
requestAccepted:boolean;
end;
// Main graphics-system implementation for OpenGL.
// Owns and wires all rendering subsystems (target, shaders, resman, text, draw).
// Lifecycle is controlled via IGraphicsSystem (Init/Done).
// Important: all GL-owning services must be released in Done BEFORE the platform
// destroys the GL context, otherwise GPU resources cannot be deleted safely.
TOpenGL=class(TInterfacedObject,IGraphicsSystem,IGraphicsSystemConfig)
procedure Init(window:TWindow);
procedure InitThreadContext(window:TWindow);
procedure Done;
function GetVersion:single;
function GetName:string8;
// IGraphicsSystemConfig
procedure ChoosePixelFormats(out trueColor,trueColorAlpha,rtTrueColor,rtTrueColorAlpha:TImagePixelFormat;
economyMode:boolean=false);
function ShouldUseTextureAsDefaultRT:boolean;
function SetVSyncDivider(n:integer):boolean; // 0 - unlimited FPS, 1 - use monitor refresh rate
function QueryMaxRTSize:integer;
// Core interfaces
function config:IGraphicsSystemConfig;
function resman:IResourceManager;
function target:IRenderTarget;
function shader:IShader; inline;
function clip:IClipping; inline;
function transform:ITransformation;
function draw:IDrawer; inline;
function txt:ITextDrawer;
// Functions
procedure PresentFrame;
procedure CopyFromBackbuffer(srcX,srcY:integer;image:TRawImage);
function GetPixelValue(X,Y:integer):cardinal;
procedure BeginPaint(target:TTexture);
procedure EndPaint;
procedure SetCullMode(mode:TCullMode);
procedure Restore;
procedure DrawDebugOverlay(idx:integer);
procedure PostDebugMsg(st:string8;id:integer=0);
procedure Breakpoint;
// For internal use
protected
glVersion,glRenderer:string8;
glVersionNum:single;
wnd:TWindow;
class threadvar
canPaint:integer;
// Explicit owners for interfaced singletons created in Init.
// They are released in Done via :=nil to trigger deterministic destruction.
ownRenderTarget:IRenderTarget;
ownTransformation:ITransformation;
ownClipping:IClipping;
ownShader:IShader;
ownResMan:IResourceManager;
end;
var
debugGL:boolean = true;
glDefaultVAO:cardinal = 0;
threadvar
debugGroupDepth:integer;
var
// OpenGL context request template and actual context info.
// Template is configured by app-level code before game startup.
oglContextTemplate:TOpenGLContextDesc;
oglContextInfo:TOpenGLContextDesc;
procedure SetupGLDebugOutputForCurrentContext(const actual:TOpenGLContextDesc; const tag:string8='');
procedure CheckForGLError(lab:integer=0); inline;
procedure PushDebugGroup(const st:String8;id:integer=0); inline;
procedure PopDebugGroup; inline;
implementation
uses
{$IFDEF DGL}dglOpenGL,{$ENDIF}
SysUtils,
Types,
Apus.Engine.Types,
Apus.Engine.Graphics,
Apus.Engine.Draw,
Apus.Engine.TextDraw,
Apus.Engine.ResManGL,
Apus.Engine.ShadersGL,
Apus.Log;
type
// Low-level bridge from engine vertex data to OpenGL draw calls.
// Used by higher-level APIs (draw/text/shaders), does not own scene resources.
TRenderDevice=class(TInterfacedObject,IRenderDevice,IRenderDeviceBindTracking)
constructor Create;
destructor Destroy; override;
procedure Reset;
procedure Draw(primType:TPrimitiveType;primCount:integer;vertices:pointer;
vertexLayout:TVertexLayout);
// Draw primitives using pre-configured attributes
//procedure DrawBuffers(primType:TPrimitiveType;primCount:integer);
// Draw indexed primitives using in-memory buffers
procedure DrawIndexed(primType:TPrimitiveType;vertices:pointer;indices:pointer;
vertexLayout:TVertexLayout; primCount:integer); overload;
// Ranged version
procedure DrawIndexed(primType:TPrimitiveType;vertices:pointer;indices:pointer;
vertexLayout:TVertexLayout; vrtStart,vrtCount:integer; indStart,primCount:integer); overload;
procedure DrawInstanced(primType:TPrimitiveType;vertices:pointer;indices:pointer;
vertexLayout:TVertexLayout;primCount,instances:integer); overload;
procedure DrawInstanced(primType:TPrimitiveType;vertices:pointer;
vertexLayout:TVertexLayout;primCount,instances:integer); overload;
procedure UseExtraVertexData(vertices:pointer;vertexLayout:TVertexLayout);
procedure SetVertexDataDivisors(baseDivisor,extraDivisor:integer);
{ // Draw primitives using custom buffers
procedure DrawBuffer(primType:TPrimitiveType;vb:TVertexBuffer;ib:TIndexBuffer); overload;
// Draw indexed primitives using built-in buffer
procedure DrawBuffer(primType:integer;vertexBuf,indBuf:TPainterBuffer;
stride:integer;vrtStart,vrtCount:integer; indStart,primCount:integer); overload;}
protected
class threadvar
actualAttribArrays:shortint; // number of enabled attrib arrays (-1 = unknown)
lastVertices:pointer;
lastLayout:TVertexLayout;
lastStride:integer;
lastArrayBuffer:GLint;
boundArrayBuffer:GLint;
boundElementArrayBuffer:GLint;
baseDivisor,extraDivisor:integer;
extraVertices:pointer;
extraLayout:TVertexLayout;
divisors:array[0..9] of integer;
streamVB,streamIB:cardinal;
streamVBSize,streamIBSize:integer;
threadReady:boolean;
function PrimitiveVertexCount(primType:TPrimitiveType;primCount:integer):integer;
function PrimitiveIndexCount(primType:TPrimitiveType;primCount:integer):integer;
function IsCoreProfile:boolean;
procedure EnsureThreadState;
procedure EnsureStreamVB(requiredSize:integer);
procedure EnsureStreamIB(requiredSize:integer);
procedure UploadStreamVertices(vertices:pointer;vertexLayout:TVertexLayout;vertexCount:integer);
procedure UploadStreamIndices(indices:pointer;indexCount:integer);
procedure SetupAttributes(vertices:pointer;vertexLayout:TVertexLayout);
procedure TrackArrayBufferBinding(buffer:cardinal);
procedure TrackElementBufferBinding(buffer:cardinal);
end;
// OpenGL-specific render-target implementation.
// Applies viewport/scissor/blend/depth states for backbuffer and texture RTs.
TGLRenderTargetAPI=class(TRendertargetAPI)
constructor Create;
procedure Backbuffer; override;
procedure Texture(tex:TTexture); override;
procedure Clear(color:cardinal;zbuf:single=0;stencil:integer=-1); override;
procedure ClearDepth(zbuf:single=0;stencil:integer=-1); override;
procedure Viewport(oX,oY,VPwidth,VPheight,renderWidth,renderHeight:integer); override;
procedure UseDepthBuffer(test:TDepthBufferTest;writeEnable:boolean=true); override;
procedure BlendMode(blend:TBlendingMode); override;
procedure Clip(x,y,w,h:integer); override;
procedure ApplyMask; override;
procedure Resized(newWidth,newHeight:integer); override;
protected
class threadvar
scissor:boolean;
backBufferWidth,backBufferHeight:integer;
threadReady:boolean;
procedure EnsureThreadState;
procedure ClearBuffers(fColor,fDepth,fStencil:boolean;color:cardinal;zbuf:single;stencil:integer);
end;
//textureManager:TResource;
procedure CheckForGLError(lab:integer=0); inline;
var
error:cardinal;
begin
if debugGL then begin
error:=glGetError;
if error<>GL_NO_ERROR then begin
raise EError.Create('GL Error %d: code %d (%x)',[lab,error,error]);
end;
end;
end;
function GLProfileToString(profile:TOpenGLContextProfile):string;
begin
case profile of
oglpCompatibility:result:='compatibility';
oglpCore:result:='core';
else result:='any';
end;
end;
function GLContextRequestToString(const request:TOpenGLContextDesc):string;
begin
result:='min='+IntToStr(request.minMajor)+'.'+IntToStr(request.minMinor)+
', preferHighest='+BoolToStr(request.preferHighest,true)+
', profile='+GLProfileToString(request.profile)+
', debug='+BoolToStr(request.debugContext,true)+
', forward='+BoolToStr(request.forwardCompatible,true);
end;
function GLContextInfoToString(const info:TOpenGLContextDesc):string;
begin
result:='version='+IntToStr(info.actualMajor)+'.'+IntToStr(info.actualMinor)+
', profile='+GLProfileToString(info.profile)+
', debug='+BoolToStr(info.debugContext,true)+
', forward='+BoolToStr(info.forwardCompatible,true)+
', accepted='+BoolToStr(info.requestAccepted,true);
end;
procedure HandleGLDebugMessage(source,typ,id,severity:GLenum;len:GLsizei;const message_:PGLchar;userParam:PGLvoid); {$IFDEF DGL_WIN}stdcall{$ELSE}cdecl{$ENDIF}; forward;
procedure SetupGLDebugOutputForCurrentContext(const actual:TOpenGLContextDesc; const tag:string8='');
var
where:string8;
begin
if not actual.debugContext then exit;
if tag<>'' then
where:=' ('+tag+')'
else
where:='';
// Callback registration is per-context. Each shared context must set it explicitly.
if @glDebugMessageCallback<>nil then begin
glEnable(GL_DEBUG_OUTPUT);
if @glDebugMessageControl<>nil then
glDebugMessageControl(GL_DONT_CARE,GL_DONT_CARE,GL_DEBUG_SEVERITY_NOTIFICATION,0,nil,GL_FALSE);
glDebugMessageCallback(TGLDEBUGPROC(@HandleGLDebugMessage),nil);
Log.Force('OpenGL debug callback enabled (KHR)'+where);
end else
if @glDebugMessageCallbackARB<>nil then begin
if @glDebugMessageControlARB<>nil then
glDebugMessageControlARB(GL_DONT_CARE,GL_DONT_CARE,GL_DEBUG_SEVERITY_NOTIFICATION,0,nil,GL_FALSE);
glDebugMessageCallbackARB(@HandleGLDebugMessage,nil);
Log.Force('OpenGL debug callback enabled (ARB)'+where);
end else
Log.Warn('Debug context requested but debug callback API is not available'+where);
end;
{ TOpenGL }
procedure TOpenGL.Init(window:TWindow);
var
i:integer;
cnt:GLINT;
request:TOpenGLContextDesc;
actual:TOpenGLContextDesc;
exList:string;
begin
Log.Msg('Init OpenGL');
exList:='';
wnd:=window;
request:=oglContextTemplate;
actual:=request;
Log.Force('OpenGL context request: '+GLContextRequestToString(request));
{$IFDEF DGL}
InitOpenGL;
{$ENDIF}
wnd.InitGraph;
actual:=oglContextInfo;
{$IFDEF DGL}
ReadImplementationProperties;
ReadExtensions;
{$ENDIF}
CheckForGLError(011);
glVersion:=glGetString(GL_VERSION);
glRenderer:=glGetString(GL_RENDERER);
if actual.actualMajor=0 then begin
glVersionNum:=GetVersion;
actual.actualMajor:=trunc(glVersionNum);
actual.actualMinor:=round((glVersionNum-actual.actualMajor)*10);
end;
if (request.profile=oglpCore) and ((not actual.requestAccepted) or (actual.profile<>oglpCore)) then
raise EFatalError.Create('Core profile was requested but not created.'#13#10+
'Requested: '+GLContextRequestToString(request)+#13#10+
'Actual: '+GLContextInfoToString(actual));
oglContextInfo:=actual;
Log.Force('OpenGL context actual: '+GLContextInfoToString(oglContextInfo));
// Stage 7 debug tooling:
// callback is context-local, so it must be configured for every context.
SetupGLDebugOutputForCurrentContext(actual,'main');
Log.Force('OpenGL version: '+glVersion);
Log.Force('OpenGL vendor: '+PAnsiChar(glGetString(GL_VENDOR)));
Log.Force('OpenGL renderer: '+glRenderer);
if not GL_VERSION_3_0 then
raise EFatalError.Create('OpenGL 3.0 or higher required!'#13#10'Please update your video drivers.');
glGetIntegerv(GL_NUM_EXTENSIONS,@cnt);
for i:=0 to cnt-1 do
exList:=exList+#13#10+PAnsiChar(glGetStringi(GL_EXTENSIONS,i));
Log.Force('OpenGL extensions: '+exList);
CheckForGLError(012);
glVersionNum:=GetVersion;
// Core profile requires a bound VAO for attribute setup.
if (oglContextInfo.profile=oglpCore) and GL_VERSION_3_0 then begin
glGenVertexArrays(1,@glDefaultVAO);
glBindVertexArray(glDefaultVAO);
Log.Force('OpenGL default VAO created: '+IntToStr(glDefaultVAO));
end;
// Create API objects
// TODO: add try/except with rollback — if a later constructor fails, earlier objects remain dangling
renderDevice:=TRenderDevice.Create;
renderTargetAPI:=TGLRenderTargetAPI.Create;
transformationAPI:=TTransformationAPI.Create;
clippingAPI:=TClippingAPI.Create;
shadersAPI:=TGLShadersAPI.Create;
ownRenderTarget:=renderTargetAPI;
ownTransformation:=transformationAPI;
ownClipping:=clippingAPI;
ownShader:=shadersAPI;
// API shortcut ownership rule:
// these global interface refs are assigned and cleared only by TOpenGL (Init/Done).
Apus.Engine.API.transform:=transformationAPI;
Apus.Engine.API.shader:=shadersAPI;
CheckForGLError(013);
TGLResourceManager.Create;
ownResMan:=resourceManagerGL;
TDrawer.Create;
TTextDrawer.Create;
Apus.Engine.API.draw:=drawer;
Apus.Engine.API.txt:=textDrawer;
InitThreadContext(window);
CheckForGLError(014);
end;
procedure TOpenGL.InitThreadContext(window:TWindow);
begin
wnd:=window;
// Prime per-thread backend state for deterministic startup.
// Keep lazy EnsureThreadState as fallback in all subsystems.
target.Resized(window.windowWidth,window.windowHeight);
target.Viewport(0,0,window.windowWidth,window.windowHeight,window.renderWidth,window.renderHeight);
shader.Reset;
clip.Nothing;
clip.Restore;
transform.DefaultView;
end;
procedure TOpenGL.Done;
begin
Log.Msg('OGL Done start');
// Release objects in explicit order while GL context is still alive.
// Required pre-context-loss cleanup:
// 1) Text and drawing helpers: cached text texture, neutral texture, temp shader.
// 2) Shader API: compiled GL programs/shaders.
// 3) Resource manager: textures, FBO/RBO, vertex/index buffers.
// 4) Core state APIs and render device.
// This order ensures resource users die before resource owners.
// 1) Text and drawing helpers own textures/shaders.
Apus.Engine.API.txt:=nil;
textDrawer:=nil;
Apus.Engine.API.draw:=nil;
drawer:=nil;
// 2) Shader system can own GL programs.
Apus.Engine.API.shader:=nil;
ownShader:=nil;
shadersAPI:=nil;
// 3) Resource manager should go after all texture users.
ownResMan:=nil;
resourceManagerGL:=nil;
// 4) Core render APIs.
Apus.Engine.API.transform:=nil;
ownTransformation:=nil;
ownClipping:=nil;
ownRenderTarget:=nil;
transformationAPI:=nil;
clippingAPI:=nil;
renderTargetAPI:=nil;
renderDevice:=nil;
if glDefaultVAO<>0 then begin
glDeleteVertexArrays(1,@glDefaultVAO);
glDefaultVAO:=0;
end;
Log.Msg('OGL Done finished');
end;
procedure TOpenGL.PostDebugMsg(st:string8;id:integer=0);
begin
if (length(st)=0) or (@glDebugMessageInsert=nil) then exit;
glDebugMessageInsert(GL_DEBUG_SOURCE_APPLICATION,GL_DEBUG_TYPE_MARKER, id, GL_DEBUG_SEVERITY_LOW,
length(st),@st[1]);
end;
procedure TOpenGL.PresentFrame;
begin
PostDebugMsg('PresentFrame');
wnd.PresentFrame;
end;
function TOpenGL.QueryMaxRTSize:integer;
begin
result:=resourceManagerGL.maxRTsize;
end;
procedure TOpenGL.Restore;
begin
renderDevice.Reset;
shader.Reset;
transform.DefaultView;
SetCullMode(cullNone);
end;
procedure TOpenGL.SetCullMode(mode: TCullMode);
begin
case mode of
cullCCW:begin
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
end;
cullCW:begin
glEnable(GL_CULL_FACE);
glCullFace(GL_FRONT);
end;
cullNone:glDisable(GL_CULL_FACE);
end;
end;
function TOpenGL.SetVSyncDivider(n: integer):boolean;
begin
result:=false;
{$IFDEF MSWINDOWS}
if WGL_EXT_swap_control then begin
wglSwapIntervalEXT(n);
Log.Msg('VSync: swap interval=%d',[n]);
exit(true);
end;
{$ENDIF}
end;
procedure TOpenGL.BeginPaint(target: TTexture);
var
rw,rh:integer;
grp:String8;
begin
if target=nil then
PostDebugMsg('BeginPaint')
else
PostDebugMsg('BeginPaint: '+target.name);
if target=nil then
grp:='Frame'
else
grp:='RenderTarget:'+target.name;
// Stage 7: balanced debug groups are required for stable NSight event tree.
// Group depth is guarded in PopDebugGroup to survive unmatched EndPaint calls.
PushDebugGroup(grp);
{if (canPaint>0) and (target=curTarget) then
raise EWarning.Create('BP: target already set');}
if canPaint>0 then
renderTargetAPI.Push;
inc(canPaint);
shader.Reset;
drawer.Reset;
renderTargetAPI.Texture(target);
renderTargetAPI.Viewport(0,0,-1,-1);
renderTargetAPI.BlendMode(blAlpha);
transformationAPI.DefaultView;
clip.Nothing;
CheckForGLError;
end;
procedure TOpenGL.EndPaint;
begin
if canPaint<=0 then begin
Log.Warn('EndPaint called without matching BeginPaint');
exit;
end;
/// TODO: flush any draw caches
dec(canPaint);
if canPaint>0 then begin
renderTargetAPI.Pop;
renderTargetAPI.BlendMode(blAlpha);
transformationAPI.DefaultView;
end;
clippingAPI.Restore;
PopDebugGroup;
end;
procedure TOpenGL.Breakpoint;
begin
glFlush;
end;
procedure TOpenGL.ChoosePixelFormats(out trueColor, trueColorAlpha, rtTrueColor,
rtTrueColorAlpha: TImagePixelFormat; economyMode: boolean);
begin
trueColor:=ipfXRGB;
trueColorAlpha:=ipfARGB;
rtTrueColor:=ipfXRGB;
rtTrueColorAlpha:=ipfARGB;
end;
procedure TOpenGL.CopyFromBackbuffer(srcX,srcY:integer;image:TRawImage);
var
fbo:gluint;
begin
ASSERT(image.pixelFormat in [ipfARGB,ipfXRGB]);
glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING,@fbo);
glBindBuffer(GL_PIXEL_PACK_BUFFER,0);
if fbo=0 then glReadBuffer(GL_BACK)
else glReadBuffer(GL_COLOR_ATTACHMENT0);
image.Lock;
glReadPixels(srcX,srcY,image.Width,image.Height,GL_BGRA,GL_UNSIGNED_BYTE,image.data);
if fbo<>0 then // flip vertically: FBO origin is bottom-left
image.FlipVertical;
image.Unlock;
CheckForGLError(021);
end;
function TOpenGL.GetPixelValue(x,y:integer):cardinal;
var
fbo:gluint;
begin
glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING,@fbo);
if fbo<>0 then exit(0);
glBindBuffer(GL_PIXEL_PACK_BUFFER,0);
glReadBuffer(GL_BACK);
glReadPixels(x,target.height-y-1,1,1,GL_BGRA,GL_UNSIGNED_BYTE,@result);
CheckForGLError(022);
end;
function TOpenGL.ShouldUseTextureAsDefaultRT:boolean;
begin
result:=GL_VERSION_3_0;
end;
function TOpenGL.config:IGraphicsSystemConfig;
begin
result:=self;
end;
function TOpenGL.shader:IShader;
begin
result:=shadersAPI;
end;
function TOpenGL.clip:IClipping;
begin
result:=clippingAPI;
end;
function TOpenGL.target:IRenderTarget;
begin
result:=renderTargetAPI;
end;
function TOpenGL.resman:IResourceManager;
begin
result:=resourceManagerGL;
end;
function TOpenGL.transform:ITransformation;
begin
result:=transformationAPI;
end;
function TOpenGL.txt:ITextDrawer;
begin
result:=textDrawer;
end;
function TOpenGL.draw:IDrawer;
begin
result:=drawer;
end;
procedure TOpenGL.DrawDebugOverlay(idx: integer);
begin
end;
function TOpenGL.GetName: string8;
begin
result:=className;
end;
function TOpenGL.GetVersion: single;
begin
result:=1.4;
if GL_VERSION_1_5 then result:=1.5;
if GL_VERSION_2_0 then result:=2.0;
if GL_VERSION_2_1 then result:=2.1;
if GL_VERSION_3_0 then result:=3.0;
if GL_VERSION_3_1 then result:=3.1;
if GL_VERSION_3_2 then result:=3.2;
if GL_VERSION_3_3 then result:=3.3;
if GL_VERSION_4_0 then result:=4.0;
if GL_VERSION_4_1 then result:=4.1;
if GL_VERSION_4_2 then result:=4.2;
if GL_VERSION_4_3 then result:=4.3;
if GL_VERSION_4_4 then result:=4.4;
if GL_VERSION_4_5 then result:=4.5;
if GL_VERSION_4_6 then result:=4.6;
end;
{ TRenderDevice }
constructor TRenderDevice.Create;
begin
EnsureThreadState;
end;
destructor TRenderDevice.Destroy;
begin
if streamVB<>0 then glDeleteBuffers(1,@streamVB);
if streamIB<>0 then glDeleteBuffers(1,@streamIB);
inherited;
end;
function TRenderDevice.PrimitiveVertexCount(primType:TPrimitiveType;primCount:integer):integer;
begin
case primtype of
LINE_LIST:result:=primCount*2;
LINE_STRIP:result:=primCount+1;
TRG_LIST:result:=primCount*3;
TRG_FAN,TRG_STRIP:result:=primCount+2;
else result:=0;
end;
end;
function TRenderDevice.PrimitiveIndexCount(primType:TPrimitiveType;primCount:integer):integer;
begin
result:=PrimitiveVertexCount(primType,primCount);
end;
function TRenderDevice.IsCoreProfile:boolean;
begin
EnsureThreadState;
result:=oglContextInfo.profile=oglpCore;
end;
procedure TRenderDevice.EnsureThreadState;
var
i:integer;
begin
if threadReady then exit;
streamVB:=0;
streamIB:=0;
streamVBSize:=0;
streamIBSize:=0;
lastVertices:=nil;
lastLayout.stride:=0;
lastStride:=0;
lastArrayBuffer:=-1;
boundArrayBuffer:=0;
boundElementArrayBuffer:=0;
baseDivisor:=0;
extraDivisor:=0;
extraVertices:=nil;
extraLayout.stride:=0;
actualAttribArrays:=-1;
for i:=0 to high(divisors) do
divisors[i]:=-1;
threadReady:=true;
end;
procedure TRenderDevice.TrackArrayBufferBinding(buffer:cardinal);
begin
EnsureThreadState;
boundArrayBuffer:=buffer;
end;
procedure PushDebugGroup(const st:String8;id:integer=0);
begin
// Functions may be absent on old drivers even with debug context requested.
if (length(st)=0) or (@glPushDebugGroup=nil) then exit;
glPushDebugGroup(GL_DEBUG_SOURCE_APPLICATION,id,length(st),@st[1]);
inc(debugGroupDepth);
end;
procedure PopDebugGroup;
begin
// Keep this safe for error paths: never pop below zero.
if (debugGroupDepth<=0) or (@glPopDebugGroup=nil) then exit;
glPopDebugGroup;
dec(debugGroupDepth);
end;
procedure HandleGLDebugMessage(source,typ,id,severity:GLenum;len:GLsizei;const message_:PGLchar;userParam:PGLvoid); {$IFDEF DGL_WIN}stdcall{$ELSE}cdecl{$ENDIF};
var
st:string8;
srcName,typeName,severityName:string8;
function DebugSourceName(v:GLenum):string8; inline;
begin
case v of
GL_DEBUG_SOURCE_API:result:='API';
GL_DEBUG_SOURCE_WINDOW_SYSTEM:result:='WIN';
GL_DEBUG_SOURCE_SHADER_COMPILER:result:='SHDR';
GL_DEBUG_SOURCE_THIRD_PARTY:result:='3RD';
GL_DEBUG_SOURCE_APPLICATION:result:='APP';
GL_DEBUG_SOURCE_OTHER:result:='OTHER';
else result:='SRC'+IntToHex(v,4);
end;
end;
function DebugTypeName(v:GLenum):string8; inline;
begin
case v of
GL_DEBUG_TYPE_ERROR:result:='ERROR';
GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:result:='DEPR';
GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:result:='UNDEF';
GL_DEBUG_TYPE_PORTABILITY:result:='PORT';
GL_DEBUG_TYPE_PERFORMANCE:result:='PERF';
GL_DEBUG_TYPE_OTHER:result:='OTHER';
{$IFDEF DGL}
GL_DEBUG_TYPE_MARKER:result:='MARK';
{$ENDIF}
else result:='TYPE'+IntToHex(v,4);
end;
end;
function DebugSeverityName(v:GLenum):string8; inline;
begin
case v of
GL_DEBUG_SEVERITY_HIGH:result:='HIGH';
GL_DEBUG_SEVERITY_MEDIUM:result:='MED';
GL_DEBUG_SEVERITY_LOW:result:='LOW';
GL_DEBUG_SEVERITY_NOTIFICATION:result:='NOTE';
else result:='SEV'+IntToHex(v,4);
end;
end;
begin
// Driver callback for runtime GL diagnostics.
// We keep source/type/id/severity in raw form so logs are easy to compare
// against vendor docs and NSight event metadata.
if message_=nil then exit;
if severity=GL_DEBUG_SEVERITY_NOTIFICATION then exit;
if id=131154 then exit; // pixel transfer sync warning (expected during robot API readback)
// Stage 7: leave message mapping simple and log raw enums for cross-driver diagnostics.
st:=PAnsiChar(message_);
srcName:=DebugSourceName(source);
typeName:=DebugTypeName(typ);
severityName:=DebugSeverityName(severity);
// SystemMessage routes to log + debugger console, and can be configured
// by SystemMessageFlags to escalate into EFatalError (smRaise) for strict runs.
SystemMessage(Format('[GLDBG][%s][%s][%s] id=%d: %s',[srcName,typeName,severityName,id,st]));
end;
procedure TRenderDevice.TrackElementBufferBinding(buffer:cardinal);
begin
EnsureThreadState;
boundElementArrayBuffer:=buffer;
end;
procedure TRenderDevice.EnsureStreamVB(requiredSize:integer);
begin
EnsureThreadState;
if streamVB=0 then begin
glGenBuffers(1,@streamVB);
ASSERT(streamVB<>0);
end;
if requiredSize<=streamVBSize then exit;
if streamVBSize=0 then
streamVBSize:=1024;
while streamVBSize<requiredSize do
streamVBSize:=streamVBSize*2;
glBindBuffer(GL_ARRAY_BUFFER,streamVB);
TrackArrayBufferBinding(streamVB);
// TODO(low): reduce bind churn around stream buffer growth/upload path (keep one bind when possible).
glBufferData(GL_ARRAY_BUFFER,streamVBSize,nil,GL_STREAM_DRAW);
end;
procedure TRenderDevice.EnsureStreamIB(requiredSize:integer);
begin
EnsureThreadState;
if streamIB=0 then begin
glGenBuffers(1,@streamIB);
ASSERT(streamIB<>0);
end;
if requiredSize<=streamIBSize then exit;
if streamIBSize=0 then
streamIBSize:=1024;
while streamIBSize<requiredSize do
streamIBSize:=streamIBSize*2;
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,streamIB);
TrackElementBufferBinding(streamIB);
// TODO(low): reduce bind churn around stream buffer growth/upload path (keep one bind when possible).
glBufferData(GL_ELEMENT_ARRAY_BUFFER,streamIBSize,nil,GL_STREAM_DRAW);
end;
procedure TRenderDevice.UploadStreamVertices(vertices:pointer;vertexLayout:TVertexLayout;vertexCount:integer);
var
bytes:integer;
begin
EnsureThreadState;
ASSERT(vertices<>nil);
bytes:=vertexCount*vertexLayout.stride;
EnsureStreamVB(bytes);
glBindBuffer(GL_ARRAY_BUFFER,streamVB);
TrackArrayBufferBinding(streamVB);
glBufferSubData(GL_ARRAY_BUFFER,0,bytes,vertices);
end;
procedure TRenderDevice.UploadStreamIndices(indices:pointer;indexCount:integer);
var
bytes:integer;
begin
EnsureThreadState;
ASSERT(indices<>nil);
bytes:=indexCount*2;
EnsureStreamIB(bytes);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,streamIB);
TrackElementBufferBinding(streamIB);
glBufferSubData(GL_ELEMENT_ARRAY_BUFFER,0,bytes,indices);
end;
procedure TRenderDevice.Draw(primType:TPrimitiveType; primCount: integer; vertices: pointer;
vertexLayout:TVertexLayout);
var
vertexCount:integer;
useStream:boolean;
begin
EnsureThreadState;
shader.Apply(vertexLayout);
vertexCount:=PrimitiveVertexCount(primType,primCount);
useStream:=vertices<>nil;
if useStream then begin
UploadStreamVertices(vertices,vertexLayout,vertexCount);
vertices:=nil; // attributes are offsets in bound stream VBO
end;
SetupAttributes(vertices,vertexLayout);
case primtype of
LINE_LIST:glDrawArrays(GL_LINES,0,primCount*2);
LINE_STRIP:glDrawArrays(GL_LINE_STRIP,0,primCount+1);
TRG_LIST:glDrawArrays(GL_TRIANGLES,0,primCount*3);
TRG_FAN:glDrawArrays(GL_TRIANGLE_FAN,0,primCount+2);
TRG_STRIP:glDrawArrays(GL_TRIANGLE_STRIP,0,primCount+2);
end;
CheckForGLError(111);
end;
procedure TRenderDevice.DrawIndexed(primType:TPrimitiveType;vertices:pointer;indices:pointer;
vertexLayout:TVertexLayout;primCount:integer);
var
indexCount,vertexCount:integer;
useStream:boolean;
begin
EnsureThreadState;
shader.Apply(vertexLayout);
indexCount:=PrimitiveIndexCount(primType,primCount);
// TODO(low): consider removing this overload or extending it with vrtCount; stream upload without vertex count is unsafe.
useStream:=false;
if useStream then begin
vertexCount:=indexCount;
UploadStreamVertices(vertices,vertexLayout,vertexCount);
UploadStreamIndices(indices,indexCount);
vertices:=nil;
indices:=nil;
end else begin
if IsCoreProfile and ((vertices<>nil) or (indices<>nil)) then
ASSERT(false,'Use ranged DrawIndexed(...) with vrtCount for core-profile RAM-backed indexed draws');
if not IsCoreProfile then begin
if vertices<>nil then begin
glBindBuffer(GL_ARRAY_BUFFER,0); // client memory pointers require unbound VBO in compatibility mode
TrackArrayBufferBinding(0);
end;
if indices<>nil then begin
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0); // client index pointers require unbound EBO
TrackElementBufferBinding(0);
end;
end;
end;
SetupAttributes(vertices,vertexLayout);
case primtype of
LINE_LIST:glDrawElements(GL_LINES,primCount*2,GL_UNSIGNED_SHORT,indices);
LINE_STRIP:glDrawElements(GL_LINE_STRIP,primCount+1,GL_UNSIGNED_SHORT,indices);
TRG_LIST:glDrawElements(GL_TRIANGLES,primCount*3,GL_UNSIGNED_SHORT,indices);
TRG_FAN:glDrawElements(GL_TRIANGLE_FAN,primCount+2,GL_UNSIGNED_SHORT,indices);
TRG_STRIP:glDrawElements(GL_TRIANGLE_STRIP,primCount+2,GL_UNSIGNED_SHORT,indices);
end;
CheckForGLError(112);
end;
procedure TRenderDevice.DrawIndexed(primType:TPrimitiveType;vertices:pointer;indices:pointer;
vertexLayout:TVertexLayout; vrtStart,vrtCount:integer; indStart,primCount:integer);
var
indexCount,vertexCount:integer;
useStream:boolean;
begin
EnsureThreadState;
shader.Apply(vertexLayout);
indexCount:=PrimitiveIndexCount(primType,primCount);
useStream:=vertices<>nil;
if useStream then begin
// Keep original index values by uploading vertices up to the range end.
vertexCount:=vrtStart+vrtCount;
UploadStreamVertices(vertices,vertexLayout,vertexCount);
UploadStreamIndices(indices,indexCount);
vertices:=nil;
indices:=nil;
end else
if not IsCoreProfile then begin
if vertices<>nil then begin
glBindBuffer(GL_ARRAY_BUFFER,0); // client memory pointers require unbound VBO in compatibility mode
TrackArrayBufferBinding(0);
end;
if indices<>nil then begin
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0); // client index pointers require unbound EBO
TrackElementBufferBinding(0);
end;
end;
SetupAttributes(vertices,vertexLayout);
case primtype of
LINE_LIST:glDrawRangeElements(GL_LINES,vrtStart,vrtStart+vrtCount-1,primCount*2,GL_UNSIGNED_SHORT,indices);
LINE_STRIP:glDrawRangeElements(GL_LINE_STRIP,vrtStart,vrtStart+vrtCount-1,primCount+1,GL_UNSIGNED_SHORT,indices);
TRG_LIST:glDrawRangeElements(GL_TRIANGLES,vrtStart,vrtStart+vrtCount-1,primCount*3,GL_UNSIGNED_SHORT,indices);
TRG_FAN:glDrawRangeElements(GL_TRIANGLE_FAN,vrtStart,vrtStart+vrtCount-1,primCount+2,GL_UNSIGNED_SHORT,indices);
TRG_STRIP:glDrawRangeElements(GL_TRIANGLE_STRIP,vrtStart,vrtStart+vrtCount-1,primCount+2,GL_UNSIGNED_SHORT,indices);
end;
CheckForGLError(112);
end;
procedure TRenderDevice.DrawInstanced(primType:TPrimitiveType;vertices:pointer;indices:pointer;
vertexLayout:TVertexLayout;primCount,instances:integer);
var
indexCount,vertexCount:integer;
useStream:boolean;
begin
EnsureThreadState;
shader.Apply(vertexLayout);
indexCount:=PrimitiveIndexCount(primType,primCount);
// TODO(low): consider removing this overload or extending it with vrtCount; stream upload without vertex count is unsafe.
useStream:=false;
if useStream then begin
vertexCount:=indexCount;
UploadStreamVertices(vertices,vertexLayout,vertexCount);
UploadStreamIndices(indices,indexCount);
vertices:=nil;
indices:=nil;
end else begin
if IsCoreProfile and ((vertices<>nil) or (indices<>nil)) then
ASSERT(false,'Use ranged DrawIndexed(...) with vrtCount for core-profile RAM-backed indexed draws');
if not IsCoreProfile then begin
if vertices<>nil then begin
glBindBuffer(GL_ARRAY_BUFFER,0); // client memory pointers require unbound VBO in compatibility mode
TrackArrayBufferBinding(0);
end;
if indices<>nil then begin
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0); // client index pointers require unbound EBO
TrackElementBufferBinding(0);
end;
end;
end;
SetupAttributes(vertices,vertexLayout);
case primtype of
LINE_LIST:glDrawElementsInstanced(GL_LINES,primCount*2,GL_UNSIGNED_SHORT,indices,instances);
LINE_STRIP:glDrawElementsInstanced(GL_LINE_STRIP,primCount+1,GL_UNSIGNED_SHORT,indices,instances);
TRG_LIST:glDrawElementsInstanced(GL_TRIANGLES,primCount*3,GL_UNSIGNED_SHORT,indices,instances);
TRG_FAN:glDrawElementsInstanced(GL_TRIANGLE_FAN,primCount+2,GL_UNSIGNED_SHORT,indices,instances);
TRG_STRIP:glDrawElementsInstanced(GL_TRIANGLE_STRIP,primCount+2,GL_UNSIGNED_SHORT,indices,instances);
end;
CheckForGLError(113);
end;
procedure TRenderDevice.DrawInstanced(primType:TPrimitiveType;vertices:pointer;
vertexLayout:TVertexLayout;primCount,instances:integer);
var
vertexCount:integer;
useStream:boolean;
begin
EnsureThreadState;
shader.Apply(vertexLayout);
vertexCount:=PrimitiveVertexCount(primType,primCount);
useStream:=vertices<>nil;
if useStream then begin
UploadStreamVertices(vertices,vertexLayout,vertexCount);
vertices:=nil;
end else
if (vertices<>nil) and (not IsCoreProfile) then begin
glBindBuffer(GL_ARRAY_BUFFER,0); // client memory pointers require unbound VBO in compatibility mode
TrackArrayBufferBinding(0);