-
Notifications
You must be signed in to change notification settings - Fork 425
/
Copy pathRenderer.cs
1367 lines (1072 loc) · 53 KB
/
Renderer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using osu.Framework.Development;
using osu.Framework.Extensions.TypeExtensions;
using osu.Framework.Graphics.Primitives;
using osu.Framework.Graphics.Rendering.Vertices;
using osu.Framework.Graphics.Shaders;
using osu.Framework.Graphics.Shaders.Types;
using osu.Framework.Graphics.Textures;
using osu.Framework.IO.Stores;
using osu.Framework.Lists;
using osu.Framework.Platform;
using osu.Framework.Statistics;
using osu.Framework.Threading;
using osu.Framework.Timing;
using osuTK;
using osuTK.Graphics;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using RectangleF = osu.Framework.Graphics.Primitives.RectangleF;
using Texture = osu.Framework.Graphics.Textures.Texture;
namespace osu.Framework.Graphics.Rendering
{
/// <summary>
/// Represents a base <see cref="IRenderer"/> implementation for working renderers.
/// </summary>
public abstract class Renderer : IRenderer
{
/// <summary>
/// The length of no usage (in frames) before freeing unused resources.
/// </summary>
internal const int RESOURCE_FREE_NO_USAGE_LENGTH = 300;
protected internal abstract bool VerticalSync { get; set; }
protected internal abstract bool AllowTearing { get; set; }
protected internal Storage? CacheStorage
{
set => shaderCompilationStore.CacheStorage = value;
}
public int MaxTextureSize { get; protected set; } = 4096; // default value is to allow roughly normal flow in cases we don't have graphics context, like headless CI.
public int MaxTexturesUploadedPerFrame { get; set; } = 32;
public int MaxPixelsUploadedPerFrame { get; set; } = 1024 * 1024 * 2;
public abstract bool IsDepthRangeZeroToOne { get; }
public abstract bool IsUvOriginTopLeft { get; }
public abstract bool IsClipSpaceYInverted { get; }
public ulong FrameIndex { get; private set; }
public ref readonly MaskingInfo CurrentMaskingInfo => ref currentMaskingInfo;
public RectangleI Viewport { get; private set; }
public RectangleI Scissor { get; private set; }
public Vector2I ScissorOffset { get; private set; }
public Matrix4 ProjectionMatrix { get; private set; }
public DepthInfo CurrentDepthInfo { get; private set; }
public StencilInfo CurrentStencilInfo { get; private set; }
public WrapMode CurrentWrapModeS { get; private set; }
public WrapMode CurrentWrapModeT { get; private set; }
public bool IsMaskingActive { get; private set; }
public bool UsingBackbuffer { get; private set; }
public Texture WhitePixel => whitePixel.Value;
DepthValue IRenderer.BackbufferDepth => backBufferDepth;
public bool IsInitialised { get; private set; }
protected ClearInfo CurrentClearInfo { get; private set; }
public BlendingParameters CurrentBlendingParameters { get; private set; }
protected BlendingMask CurrentBlendingMask { get; private set; }
/// <summary>
/// Whether scissor is currently enabled.
/// </summary>
protected bool ScissorState { get; private set; }
/// <summary>
/// The current framebuffer, or null if the backbuffer is used.
/// </summary>
protected IFrameBuffer? FrameBuffer { get; private set; }
/// <summary>
/// The current shader, or null if no shader is currently bound.
/// </summary>
protected IShader? Shader { get; private set; }
private readonly ShaderCompilationStore shaderCompilationStore = new ShaderCompilationStore();
private readonly GlobalStatistic<int> statExpensiveOperationsQueued;
private readonly GlobalStatistic<int> statTextureUploadsQueued;
private readonly GlobalStatistic<int> statTextureUploadsDequeued;
private readonly GlobalStatistic<int> statTextureUploadsPerformed;
private readonly GlobalStatistic<int> vboInUse;
private readonly ConcurrentQueue<ScheduledDelegate> expensiveOperationQueue = new ConcurrentQueue<ScheduledDelegate>();
private readonly ConcurrentQueue<INativeTexture> textureUploadQueue = new ConcurrentQueue<INativeTexture>();
private readonly RendererDisposalQueue disposalQueue = new RendererDisposalQueue();
private readonly Scheduler resetScheduler = new Scheduler(() => ThreadSafety.IsDrawThread, new StopwatchClock(true)); // force no thread set until we are actually on the draw thread.
private readonly DepthValue backBufferDepth = new DepthValue();
private readonly Dictionary<string, IUniformBuffer> boundUniformBuffers = new Dictionary<string, IUniformBuffer>();
private readonly Stack<IVertexBatch<TexturedVertex2D>> quadBatches = new Stack<IVertexBatch<TexturedVertex2D>>();
private readonly List<IVertexBuffer> vertexBuffersInUse = new List<IVertexBuffer>();
private readonly List<IVertexBatch> batchResetList = new List<IVertexBatch>();
private readonly Stack<RectangleI> viewportStack = new Stack<RectangleI>();
private readonly Stack<Matrix4> projectionMatrixStack = new Stack<Matrix4>();
private readonly Stack<MaskingInfo> maskingStack = new Stack<MaskingInfo>();
private readonly Stack<RectangleI> scissorRectStack = new Stack<RectangleI>();
private readonly Stack<DepthInfo> depthStack = new Stack<DepthInfo>();
private readonly Stack<StencilInfo> stencilStack = new Stack<StencilInfo>();
private readonly Stack<Vector2I> scissorOffsetStack = new Stack<Vector2I>();
private readonly Stack<IFrameBuffer> frameBufferStack = new Stack<IFrameBuffer>();
private readonly Stack<IShader> shaderStack = new Stack<IShader>();
private readonly Stack<bool> scissorStateStack = new Stack<bool>();
private readonly INativeTexture?[] lastBoundTexture = new INativeTexture?[16];
private readonly bool[] lastBoundTextureIsAtlas = new bool[16];
// in case no other textures are used in the project, create a new atlas as a fallback source for the white pixel area (used to draw boxes etc.)
private readonly Lazy<TextureWhitePixel> whitePixel;
private readonly LockedWeakList<Texture> allTextures = new LockedWeakList<Texture>();
private IUniformBuffer<GlobalUniformData>? globalUniformBuffer;
private IVertexBatch<TexturedVertex2D>? defaultQuadBatch;
private IVertexBatch? currentActiveBatch;
private MaskingInfo currentMaskingInfo;
private int lastActiveTextureUnit;
private bool globalUniformsChanged;
private static readonly GlobalStatistic<int>[] flush_source_statistics;
static Renderer()
{
var sources = Enum.GetValues<FlushBatchSource>();
flush_source_statistics = new GlobalStatistic<int>[sources.Length];
foreach (FlushBatchSource source in sources)
flush_source_statistics[(int)source] = GlobalStatistics.Get<int>(nameof(FlushBatchSource), source.ToString());
}
protected Renderer()
{
statTextureUploadsPerformed = GlobalStatistics.Get<int>(GetType().Name, "Texture uploads performed");
statTextureUploadsDequeued = GlobalStatistics.Get<int>(GetType().Name, "Texture uploads dequeued");
statTextureUploadsQueued = GlobalStatistics.Get<int>(GetType().Name, "Texture upload queue length");
statExpensiveOperationsQueued = GlobalStatistics.Get<int>(GetType().Name, "Expensive operation queue length");
vboInUse = GlobalStatistics.Get<int>(GetType().Name, "VBOs in use");
whitePixel = new Lazy<TextureWhitePixel>(() =>
new TextureAtlas(this, TextureAtlas.WHITE_PIXEL_SIZE + TextureAtlas.PADDING, TextureAtlas.WHITE_PIXEL_SIZE + TextureAtlas.PADDING, true).WhitePixel);
}
void IRenderer.Initialise(IGraphicsSurface graphicsSurface)
{
switch (graphicsSurface.Type)
{
case GraphicsSurfaceType.OpenGL:
Trace.Assert(graphicsSurface is IOpenGLGraphicsSurface, $"Window must implement {nameof(IOpenGLGraphicsSurface)}.");
break;
case GraphicsSurfaceType.Metal:
Trace.Assert(graphicsSurface is IMetalGraphicsSurface, $"Window graphics API must implement {nameof(IMetalGraphicsSurface)}.");
break;
}
Initialise(graphicsSurface);
defaultQuadBatch = CreateQuadBatch<TexturedVertex2D>(100, 1000);
resetScheduler.AddDelayed(disposalQueue.CheckPendingDisposals, 0, true);
IsInitialised = true;
}
/// <summary>
/// Resets any states to prepare for drawing a new frame.
/// </summary>
/// <param name="windowSize">The full window size.</param>
protected internal virtual void BeginFrame(Vector2 windowSize)
{
foreach (var source in flush_source_statistics)
source.Value = 0;
globalUniformBuffer ??= ((IRenderer)this).CreateUniformBuffer<GlobalUniformData>();
Debug.Assert(defaultQuadBatch != null);
FrameIndex++;
backBufferDepth.Reset();
resetScheduler.Update();
statExpensiveOperationsQueued.Value = expensiveOperationQueue.Count;
while (expensiveOperationQueue.TryDequeue(out ScheduledDelegate? operation))
{
if (operation.State == ScheduledDelegate.RunState.Waiting)
{
operation.RunTask();
break;
}
}
globalUniformsChanged = true;
currentActiveBatch = null;
CurrentBlendingParameters = new BlendingParameters();
currentMaskingInfo = default;
foreach (var b in batchResetList)
b.ResetCounters();
batchResetList.Clear();
Shader?.Unbind();
Shader = null;
boundUniformBuffers.Clear();
viewportStack.Clear();
projectionMatrixStack.Clear();
maskingStack.Clear();
scissorRectStack.Clear();
frameBufferStack.Clear();
depthStack.Clear();
stencilStack.Clear();
scissorStateStack.Clear();
scissorOffsetStack.Clear();
shaderStack.Clear();
quadBatches.Clear();
quadBatches.Push(defaultQuadBatch);
setFrameBuffer(null, true);
Scissor = RectangleI.Empty;
ScissorOffset = Vector2I.Zero;
Viewport = RectangleI.Empty;
ProjectionMatrix = Matrix4.Identity;
PushScissorState(true);
PushViewport(new RectangleI(0, 0, (int)windowSize.X, (int)windowSize.Y));
PushScissor(new RectangleI(0, 0, (int)windowSize.X, (int)windowSize.Y));
PushScissorOffset(Vector2I.Zero);
PushMaskingInfo(new MaskingInfo
{
ScreenSpaceAABB = new RectangleI(0, 0, (int)windowSize.X, (int)windowSize.Y),
MaskingRect = new RectangleF(0, 0, windowSize.X, windowSize.Y),
ToMaskingSpace = Matrix3.Identity,
BlendRange = 1,
AlphaExponent = 1,
CornerExponent = 2.5f,
}, true);
PushDepthInfo(DepthInfo.Default);
PushStencilInfo(StencilInfo.Default);
Clear(new ClearInfo(Color4.Black));
freeUnusedVertexBuffers();
vboInUse.Value = vertexBuffersInUse.Count;
statTextureUploadsQueued.Value = textureUploadQueue.Count;
statTextureUploadsDequeued.Value = 0;
statTextureUploadsPerformed.Value = 0;
// increase the number of items processed with the queue length to ensure it doesn't get out of hand.
int targetUploads = Math.Clamp(textureUploadQueue.Count / 2, 1, MaxTexturesUploadedPerFrame);
int uploads = 0;
int uploadedPixels = 0;
// continue attempting to upload textures until enough uploads have been performed.
while (textureUploadQueue.TryDequeue(out INativeTexture? texture))
{
statTextureUploadsDequeued.Value++;
if (!texture.Upload())
continue;
statTextureUploadsPerformed.Value++;
if (++uploads >= targetUploads)
break;
if ((uploadedPixels += texture.Width * texture.Height) > MaxPixelsUploadedPerFrame)
break;
}
lastBoundTexture.AsSpan().Clear();
lastBoundTextureIsAtlas.AsSpan().Clear();
}
/// <summary>
/// Performs any last actions before a frame ends.
/// </summary>
protected internal virtual void FinishFrame()
{
FlushCurrentBatch(FlushBatchSource.FinishFrame);
}
public void ScheduleExpensiveOperation(ScheduledDelegate operation)
{
if (IsInitialised)
expensiveOperationQueue.Enqueue(operation);
}
public void ScheduleDisposal<T>(Action<T> disposalAction, T target)
{
if (IsInitialised)
disposalQueue.ScheduleDisposal(disposalAction, target);
else
disposalAction.Invoke(target);
}
/// <summary>
/// Returns an image containing the current content of the backbuffer, i.e. takes a screenshot.
/// </summary>
protected internal abstract Image<Rgba32> TakeScreenshot();
/// <summary>
/// Performs a once-off initialisation of this <see cref="Renderer"/>.
/// </summary>
protected abstract void Initialise(IGraphicsSurface graphicsSurface);
/// <summary>
/// Swaps the back buffer with the front buffer to display the new frame.
/// </summary>
protected internal abstract void SwapBuffers();
/// <summary>
/// Waits until all renderer commands have been fully executed GPU-side, as signaled by the graphics backend.
/// </summary>
/// <remarks>
/// This is equivalent to a <c>glFinish</c> call.
/// </remarks>
protected internal abstract void WaitUntilIdle();
protected internal abstract void WaitUntilNextFrameReady();
/// <summary>
/// Invoked when the rendering thread is active and commands will be enqueued.
/// This is mainly required for OpenGL renderers to mark context as current before performing GL calls.
/// </summary>
protected internal abstract void MakeCurrent();
/// <summary>
/// Invoked when the rendering thread is suspended and no more commands will be enqueued.
/// This is mainly required for OpenGL renderers to mark context as current before performing GL calls.
/// </summary>
protected internal abstract void ClearCurrent();
#region Clear
public void Clear(ClearInfo clearInfo)
{
PushDepthInfo(new DepthInfo(writeDepth: true));
PushScissorState(false);
ClearImplementation(clearInfo);
CurrentClearInfo = clearInfo;
PopScissorState();
PopDepthInfo();
}
/// <summary>
/// Informs the graphics device to clear the color and depth targets of the currently bound framebuffer.
/// </summary>
/// <param name="clearInfo">The clear parameters.</param>
protected abstract void ClearImplementation(ClearInfo clearInfo);
#endregion
#region Blending
public void SetBlend(BlendingParameters blendingParameters)
{
if (CurrentBlendingParameters == blendingParameters)
return;
FlushCurrentBatch(FlushBatchSource.SetBlend);
SetBlendImplementation(blendingParameters);
CurrentBlendingParameters = blendingParameters;
}
public void SetBlendMask(BlendingMask blendingMask)
{
if (CurrentBlendingMask == blendingMask)
return;
FlushCurrentBatch(FlushBatchSource.SetBlendMask);
SetBlendMaskImplementation(blendingMask);
CurrentBlendingMask = blendingMask;
}
/// <summary>
/// Updates the graphics device with the new blending parameters.
/// </summary>
/// <param name="blendingParameters">The blending parameters.</param>
protected abstract void SetBlendImplementation(BlendingParameters blendingParameters);
/// <summary>
/// Updates the graphics device with the new blending mask.
/// </summary>
/// <param name="blendingMask">The blending mask.</param>
protected abstract void SetBlendMaskImplementation(BlendingMask blendingMask);
#endregion
#region Viewport
public void PushViewport(RectangleI viewport)
{
var actualRect = viewport;
if (actualRect.Width < 0)
{
actualRect.X += viewport.Width;
actualRect.Width = -viewport.Width;
}
if (actualRect.Height < 0)
{
actualRect.Y += viewport.Height;
actualRect.Height = -viewport.Height;
}
this.PushOrtho(viewport);
viewportStack.Push(actualRect);
setViewport(viewport);
}
public void PopViewport()
{
Trace.Assert(viewportStack.Count > 1);
PopProjectionMatrix();
viewportStack.Pop();
setViewport(viewportStack.Peek());
}
private void setViewport(RectangleI viewport)
{
if (Viewport == viewport)
return;
SetViewportImplementation(viewport);
Viewport = viewport;
}
/// <summary>
/// Updates the graphics device with a new viewport rectangle.
/// </summary>
/// <param name="viewport">The viewport to use.</param>
protected abstract void SetViewportImplementation(RectangleI viewport);
#endregion
#region Scissor
public void PushScissor(RectangleI scissor)
{
scissorRectStack.Push(scissor);
setScissor(scissor);
}
public void PushScissorState(bool enabled)
{
scissorStateStack.Push(enabled);
setScissorState(enabled);
}
public void PushScissorOffset(Vector2I offset)
{
scissorOffsetStack.Push(offset);
setScissorOffset(offset);
}
public void PopScissor()
{
Trace.Assert(scissorRectStack.Count > 1);
scissorRectStack.Pop();
setScissor(scissorRectStack.Peek());
}
public void PopScissorState()
{
Trace.Assert(scissorStateStack.Count > 1);
scissorStateStack.Pop();
setScissorState(scissorStateStack.Peek());
}
public void PopScissorOffset()
{
Trace.Assert(scissorOffsetStack.Count > 1);
scissorOffsetStack.Pop();
setScissorOffset(scissorOffsetStack.Peek());
}
private void setScissor(RectangleI scissor)
{
if (scissor.Width < 0)
{
scissor.X += scissor.Width;
scissor.Width = -scissor.Width;
}
if (scissor.Height < 0)
{
scissor.Y += scissor.Height;
scissor.Height = -scissor.Height;
}
if (Scissor == scissor)
return;
// when rendering to a framebuffer on a backend which has the UV origin set to bottom-left (OpenGL),
// vertex positions are flipped vertically in sh_Vertex_Output.h to match that UV origin.
// for scissoring to continue to work correctly with that, the scissor box has to be inverted too.
var compensatedScissor = scissor;
if (!UsingBackbuffer && !IsUvOriginTopLeft)
compensatedScissor.Y = Viewport.Height - scissor.Bottom;
FlushCurrentBatch(FlushBatchSource.SetScissor);
SetScissorImplementation(compensatedScissor);
// do not expose the implementation detail of flipping the scissor box to Scissor readers.
Scissor = scissor;
}
private void setScissorState(bool enabled)
{
if (enabled == ScissorState)
return;
FlushCurrentBatch(FlushBatchSource.SetScissor);
SetScissorStateImplementation(enabled);
ScissorState = enabled;
}
private void setScissorOffset(Vector2I offset)
{
if (ScissorOffset == offset)
return;
FlushCurrentBatch(FlushBatchSource.SetScissor);
ScissorOffset = offset;
}
/// <summary>
/// Updates the graphics device with a new scissor rectangle.
/// </summary>
/// <param name="scissor">The scissor rectangle to use.</param>
protected abstract void SetScissorImplementation(RectangleI scissor);
/// <summary>
/// Updates the graphics device with the new scissor state.
/// </summary>
/// <param name="enabled">Whether scissor should be enabled.</param>
protected abstract void SetScissorStateImplementation(bool enabled);
#endregion
#region Projection Matrix
public void PushProjectionMatrix(Matrix4 matrix)
{
projectionMatrixStack.Push(matrix);
setProjectionMatrix(matrix);
}
public void PopProjectionMatrix()
{
Trace.Assert(projectionMatrixStack.Count > 1);
projectionMatrixStack.Pop();
setProjectionMatrix(projectionMatrixStack.Peek());
}
private void setProjectionMatrix(Matrix4 matrix)
{
if (ProjectionMatrix == matrix)
return;
FlushCurrentBatch(FlushBatchSource.SetProjection);
globalUniformsChanged = true;
ProjectionMatrix = matrix;
}
#endregion
#region Masking
public void PushMaskingInfo(in MaskingInfo maskingInfo, bool overwritePreviousScissor = false)
{
maskingStack.Push(maskingInfo);
setMaskingInfo(maskingInfo, true, overwritePreviousScissor);
}
public void PopMaskingInfo()
{
Trace.Assert(maskingStack.Count > 1);
maskingStack.Pop();
setMaskingInfo(maskingStack.Peek(), false, true);
}
private void setMaskingInfo(MaskingInfo maskingInfo, bool isPushing, bool overwritePreviousScissor)
{
if (CurrentMaskingInfo == maskingInfo)
return;
FlushCurrentBatch(FlushBatchSource.SetMasking);
if (isPushing)
{
// When drawing to a viewport that doesn't match the projection size (e.g. via framebuffers), the resultant image will be scaled
Vector2 projectionScale = new Vector2(ProjectionMatrix.Row0.X / 2, -ProjectionMatrix.Row1.Y / 2);
Vector2 viewportScale = Vector2.Multiply(Viewport.Size, projectionScale);
Vector2 location = (maskingInfo.ScreenSpaceAABB.Location - ScissorOffset) * viewportScale;
Vector2 size = maskingInfo.ScreenSpaceAABB.Size * viewportScale;
RectangleI actualRect = new RectangleI(
(int)Math.Floor(location.X),
(int)Math.Floor(location.Y),
(int)Math.Ceiling(size.X),
(int)Math.Ceiling(size.Y));
PushScissor(overwritePreviousScissor ? actualRect : RectangleI.Intersect(scissorRectStack.Peek(), actualRect));
}
else
PopScissor();
currentMaskingInfo = maskingInfo;
// Masking is enabled for as long as any masking info is active that's not the default.
IsMaskingActive = maskingStack.Count > 1;
globalUniformsChanged = true;
}
#endregion
#region Depth & Stencil
public void PushDepthInfo(DepthInfo depthInfo)
{
depthStack.Push(depthInfo);
setDepthInfo(depthInfo);
}
public void PushStencilInfo(StencilInfo stencilInfo)
{
stencilStack.Push(stencilInfo);
setStencilInfo(stencilInfo);
}
public void PopDepthInfo()
{
Trace.Assert(depthStack.Count > 1);
depthStack.Pop();
setDepthInfo(depthStack.Peek());
}
public void PopStencilInfo()
{
Trace.Assert(stencilStack.Count > 1);
stencilStack.Pop();
setStencilInfo(stencilStack.Peek());
}
private void setDepthInfo(DepthInfo depthInfo)
{
if (CurrentDepthInfo.Equals(depthInfo))
return;
FlushCurrentBatch(FlushBatchSource.SetDepthInfo);
SetDepthInfoImplementation(depthInfo);
CurrentDepthInfo = depthInfo;
}
private void setStencilInfo(StencilInfo stencilInfo)
{
if (CurrentStencilInfo.Equals(stencilInfo))
return;
FlushCurrentBatch(FlushBatchSource.SetStencilInfo);
SetStencilInfoImplementation(stencilInfo);
CurrentStencilInfo = stencilInfo;
}
/// <summary>
/// Updates the graphics device with new depth parameters.
/// </summary>
/// <param name="depthInfo">The depth parameters to use.</param>
protected abstract void SetDepthInfoImplementation(DepthInfo depthInfo);
/// <summary>
/// Updates the graphics device with new stencil parameters.
/// </summary>
/// <param name="stencilInfo">The stencil parameters to use.</param>
protected abstract void SetStencilInfoImplementation(StencilInfo stencilInfo);
#endregion
#region Batches
internal IVertexBatch<TexturedVertex2D> DefaultQuadBatch => quadBatches.Peek();
internal void PushQuadBatch(IVertexBatch<TexturedVertex2D> quadBatch) => quadBatches.Push(quadBatch);
internal void PopQuadBatch() => quadBatches.Pop();
/// <summary>
/// Notifies that a <see cref="IVertexBuffer"/> has begun being used.
/// </summary>
/// <param name="buffer">The <see cref="IVertexBuffer"/> in use.</param>
internal void RegisterVertexBufferUse(IVertexBuffer buffer) => vertexBuffersInUse.Add(buffer);
/// <summary>
/// Sets the last vertex batch used for drawing.
/// <para>
/// This is done so that various methods that change renderer state can force-draw the batch
/// before continuing with the state change.
/// </para>
/// </summary>
/// <param name="batch">The batch.</param>
internal void SetActiveBatch(IVertexBatch batch)
{
if (currentActiveBatch == batch)
return;
batchResetList.Add(batch);
FlushCurrentBatch(FlushBatchSource.SetActiveBatch);
currentActiveBatch = batch;
}
/// <summary>
/// Flushes the currently active vertex batch.
/// </summary>
/// <param name="source">The source performing the flush, for profiling purposes.</param>
protected internal void FlushCurrentBatch(FlushBatchSource? source)
{
if (currentActiveBatch?.Draw() > 0 && source != null)
flush_source_statistics[(int)source].Value++;
}
private void freeUnusedVertexBuffers()
{
foreach (var buf in vertexBuffersInUse)
{
if (buf.InUse && FrameIndex - buf.LastUseFrameIndex > RESOURCE_FREE_NO_USAGE_LENGTH)
{
// Calling Free will mark InUse as false internally, which allows the cleanup below to work.
buf.Free();
}
}
vertexBuffersInUse.RemoveAll(b => !b.InUse);
}
#endregion
#region Textures
public bool BindTexture(Texture texture, int unit, WrapMode? wrapModeS, WrapMode? wrapModeT)
{
if (!texture.Available)
throw new ObjectDisposedException(nameof(texture), "Can not bind a disposed texture.");
if (texture is TextureWhitePixel && lastBoundTextureIsAtlas[unit])
{
// We can use the special white space from any atlas texture.
return true;
}
texture.NativeTexture.Upload();
bool didBind = BindTexture(texture.NativeTexture, unit, wrapModeS ?? texture.WrapModeS, wrapModeT ?? texture.WrapModeT);
lastBoundTextureIsAtlas[unit] = texture.IsAtlasTexture;
return didBind;
}
/// <summary>
/// Binds a native texture. Generally used by internal components of renderer implementations.
/// </summary>
/// <param name="texture">The native texture to bind.</param>
/// <param name="unit">The sampling unit in which the texture is to be bound.</param>
/// <param name="wrapModeS">The texture's horizontal wrap mode.</param>
/// <param name="wrapModeT">The texture's vertex wrap mode.</param>
/// <returns>Whether the texture was successfully bound.</returns>
public bool BindTexture(INativeTexture texture, int unit = 0, WrapMode wrapModeS = WrapMode.None, WrapMode wrapModeT = WrapMode.None)
{
if (lastActiveTextureUnit == unit && lastBoundTexture[unit] == texture)
return true;
FlushCurrentBatch(FlushBatchSource.BindTexture);
if (!SetTextureImplementation(texture, unit))
return false;
if (wrapModeS != CurrentWrapModeS)
{
CurrentWrapModeS = wrapModeS;
globalUniformsChanged = true;
}
if (wrapModeT != CurrentWrapModeT)
{
CurrentWrapModeT = wrapModeT;
globalUniformsChanged = true;
}
lastBoundTexture[unit] = texture;
lastBoundTextureIsAtlas[unit] = false;
lastActiveTextureUnit = unit;
FrameStatistics.Increment(StatisticsCounterType.TextureBinds);
texture.TotalBindCount++;
return true;
}
/// <summary>
/// Unbinds any bound texture.
/// </summary>
/// <param name="unit">The sampling unit in which the texture is to be unbound.</param>
public void UnbindTexture(int unit = 0)
{
if (lastBoundTexture[unit] == null)
return;
FlushCurrentBatch(FlushBatchSource.UnbindTexture);
SetTextureImplementation(null, unit);
lastBoundTexture[unit] = null;
lastBoundTextureIsAtlas[unit] = false;
}
/// <summary>
/// Enqueues a texture to be uploaded in the next frame.
/// </summary>
/// <param name="texture">The texture to be uploaded.</param>
internal void EnqueueTextureUpload(INativeTexture texture)
{
if (!IsInitialised || textureUploadQueue.Contains(texture))
return;
textureUploadQueue.Enqueue(texture);
}
/// <summary>
/// Informs the graphics device to use the given texture for drawing.
/// </summary>
/// <param name="texture">The texture, or null to use default texture.</param>
/// <param name="unit">The sampling unit in which the texture is to be bound.</param>
/// <returns>Whether the texture was set successfully.</returns>
protected abstract bool SetTextureImplementation(INativeTexture? texture, int unit);
#endregion
#region Framebuffers
public void BindFrameBuffer(IFrameBuffer frameBuffer)
{
frameBufferStack.Push(frameBuffer);
setFrameBuffer(frameBuffer);
}
public void UnbindFrameBuffer(IFrameBuffer? frameBuffer)
{
if (FrameBuffer != frameBuffer)
return;
frameBufferStack.Pop();
setFrameBuffer(frameBufferStack.TryPeek(out var lastFramebuffer) ? lastFramebuffer : null);
}
private void setFrameBuffer(IFrameBuffer? frameBuffer, bool force = false)
{
if (frameBuffer == FrameBuffer && !force)
return;
FlushCurrentBatch(FlushBatchSource.SetFrameBuffer);
SetFrameBufferImplementation(frameBuffer);
FrameBuffer = frameBuffer;
UsingBackbuffer = frameBuffer == null;
globalUniformsChanged = true;
}
/// <summary>
/// Informs the graphics device to use the given framebuffer for drawing.
/// </summary>
/// <param name="frameBuffer">The framebuffer to use, or null to use the backbuffer (i.e. main framebuffer).</param>
protected abstract void SetFrameBufferImplementation(IFrameBuffer? frameBuffer);
/// <summary>
/// Deletes a frame buffer.
/// </summary>
/// <param name="frameBuffer">The frame buffer to delete.</param>
public void DeleteFrameBuffer(IFrameBuffer frameBuffer)
{
while (FrameBuffer == frameBuffer)
UnbindFrameBuffer(frameBuffer);
ScheduleDisposal(DeleteFrameBufferImplementation, frameBuffer);
}
protected abstract void DeleteFrameBufferImplementation(IFrameBuffer frameBuffer);
#endregion
public void DrawVertices(PrimitiveTopology topology, int vertexStart, int verticesCount)
{
if (Shader == null)
throw new InvalidOperationException("No shader bound.");
if (globalUniformsChanged)
{
globalUniformBuffer!.Data = new GlobalUniformData
{
BackbufferDraw = UsingBackbuffer,
IsDepthRangeZeroToOne = IsDepthRangeZeroToOne,
IsClipSpaceYInverted = IsClipSpaceYInverted,
IsUvOriginTopLeft = IsUvOriginTopLeft,
ProjMatrix = ProjectionMatrix,
ToMaskingSpace = currentMaskingInfo.ToMaskingSpace,
IsMasking = IsMaskingActive,
CornerRadius = currentMaskingInfo.CornerRadius,
CornerExponent = currentMaskingInfo.CornerExponent,
MaskingRect = new Vector4(
currentMaskingInfo.MaskingRect.Left,
currentMaskingInfo.MaskingRect.Top,
currentMaskingInfo.MaskingRect.Right,
currentMaskingInfo.MaskingRect.Bottom),
BorderThickness = currentMaskingInfo.BorderThickness / currentMaskingInfo.BlendRange,
BorderColour = currentMaskingInfo.BorderThickness > 0
? new Matrix4(
// TopLeft
currentMaskingInfo.BorderColour.TopLeft.SRGB.R,
currentMaskingInfo.BorderColour.TopLeft.SRGB.G,
currentMaskingInfo.BorderColour.TopLeft.SRGB.B,
currentMaskingInfo.BorderColour.TopLeft.SRGB.A,
// BottomLeft
currentMaskingInfo.BorderColour.BottomLeft.SRGB.R,
currentMaskingInfo.BorderColour.BottomLeft.SRGB.G,
currentMaskingInfo.BorderColour.BottomLeft.SRGB.B,
currentMaskingInfo.BorderColour.BottomLeft.SRGB.A,
// TopRight
currentMaskingInfo.BorderColour.TopRight.SRGB.R,
currentMaskingInfo.BorderColour.TopRight.SRGB.G,
currentMaskingInfo.BorderColour.TopRight.SRGB.B,
currentMaskingInfo.BorderColour.TopRight.SRGB.A,
// BottomRight
currentMaskingInfo.BorderColour.BottomRight.SRGB.R,
currentMaskingInfo.BorderColour.BottomRight.SRGB.G,
currentMaskingInfo.BorderColour.BottomRight.SRGB.B,
currentMaskingInfo.BorderColour.BottomRight.SRGB.A)
: globalUniformBuffer.Data.BorderColour,
MaskingBlendRange = currentMaskingInfo.BlendRange,
AlphaExponent = currentMaskingInfo.AlphaExponent,
EdgeOffset = currentMaskingInfo.EdgeOffset,
DiscardInner = currentMaskingInfo.Hollow,
InnerCornerRadius = currentMaskingInfo.Hollow
? currentMaskingInfo.HollowCornerRadius
: globalUniformBuffer.Data.InnerCornerRadius,
WrapModeS = (int)CurrentWrapModeS,
WrapModeT = (int)CurrentWrapModeT
};
globalUniformsChanged = false;
}