-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathrender_context_gl_impl.cpp
More file actions
3859 lines (3584 loc) · 144 KB
/
Copy pathrender_context_gl_impl.cpp
File metadata and controls
3859 lines (3584 loc) · 144 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
/*
* Copyright 2022 Rive
*/
#include "rive/renderer/gl/render_context_gl_impl.hpp"
#include "rive/decoders/astc_footprints.hpp"
#include "rive/renderer/gl/render_buffer_gl_impl.hpp"
#include "rive/renderer/gl/render_target_gl.hpp"
#include "rive/renderer/draw.hpp"
#ifdef RIVE_CANVAS
#include "rive/renderer/render_canvas.hpp"
#include "rive/renderer/ore/ore_context_gl.hpp"
#endif
#include "rive/renderer/render_context_impl.hpp"
#include "rive/renderer/rive_renderer.hpp"
#include "rive/renderer/texture.hpp"
#include "shaders/constants.glsl"
#include "instance_chunker.hpp"
#include "generated/shaders/advanced_blend.glsl.hpp"
#include "generated/shaders/color_ramp.glsl.hpp"
#include "generated/shaders/constants.glsl.hpp"
#include "generated/shaders/image_draw_uniforms.glsl.hpp"
#include "generated/shaders/flush_uniforms.glsl.hpp"
#include "generated/shaders/common.glsl.hpp"
#include "generated/shaders/draw_path_common.glsl.hpp"
#include "generated/shaders/draw_path.vert.hpp"
#include "generated/shaders/draw_raster_order_path.frag.hpp"
#include "generated/shaders/draw_clockwise_path.frag.hpp"
#include "generated/shaders/draw_clockwise_clip.frag.hpp"
#include "generated/shaders/draw_image_mesh.vert.hpp"
#include "generated/shaders/draw_mesh.frag.hpp"
#include "generated/shaders/draw_msaa_object.frag.hpp"
#include "generated/shaders/bezier_utils.glsl.hpp"
#include "generated/shaders/tessellate.glsl.hpp"
#include "generated/shaders/render_atlas.glsl.hpp"
#include "generated/shaders/resolve_atlas.glsl.hpp"
#include "generated/shaders/blit_texture_as_draw.glsl.hpp"
#include "generated/shaders/stencil_draw.glsl.hpp"
#ifdef RIVE_WEBGL
#include <emscripten/emscripten.h>
#include <emscripten/html5.h>
// In an effort to save space on web, and since web doesn't have ES 3.1 level
// support, don't include the atomic sources.
namespace rive::gpu::glsl
{
const char atomic_draw[] = "";
}
#define DISABLE_PLS_ATOMICS
#else
#include "generated/shaders/atomic_draw.glsl.hpp"
#endif
namespace rive::gpu
{
static bool is_tessellation_draw(gpu::DrawType drawType)
{
switch (drawType)
{
case gpu::DrawType::midpointFanPatches:
case gpu::DrawType::midpointFanCenterAAPatches:
case gpu::DrawType::outerCurvePatches:
case gpu::DrawType::msaaStrokes:
case gpu::DrawType::msaaMidpointFanBorrowedCoverage:
case gpu::DrawType::msaaMidpointFans:
case gpu::DrawType::msaaMidpointFanStencilReset:
case gpu::DrawType::msaaMidpointFanPathsStencil:
case gpu::DrawType::msaaMidpointFanPathsCover:
case gpu::DrawType::msaaOuterCubics:
return true;
case gpu::DrawType::imageRect:
case gpu::DrawType::imageMesh:
case gpu::DrawType::interiorTriangulation:
case gpu::DrawType::atlasBlit:
case gpu::DrawType::clipReset:
case gpu::DrawType::renderPassInitialize:
case gpu::DrawType::renderPassResolve:
return false;
}
RIVE_UNREACHABLE();
}
// Returns atlasDesiredRenderType, or the next supported AtlasRenderType down
// the list if it is not supported.
static RenderContextGLImpl::AtlasRenderType select_atlas_render_type(
const GLCapabilities& capabilities,
RenderContextGLImpl::AtlasRenderType atlasDesiredRenderType =
RenderContextGLImpl::AtlasRenderType::r16f)
{
switch (atlasDesiredRenderType)
{
using AtlasRenderType = RenderContextGLImpl::AtlasRenderType;
case AtlasRenderType::r16f:
if (capabilities.EXT_color_buffer_half_float)
{
return AtlasRenderType::r16f;
}
[[fallthrough]];
case AtlasRenderType::r32f:
if (capabilities.EXT_color_buffer_float &&
capabilities.EXT_float_blend)
{
// fp32 is ideal for the atlas. When there's a lot of overlap,
// fp16 can run out of precision.
return AtlasRenderType::r32f;
}
[[fallthrough]];
case AtlasRenderType::r32uiFramebufferFetch:
if (capabilities.EXT_shader_framebuffer_fetch)
{
return AtlasRenderType::r32uiFramebufferFetch;
}
[[fallthrough]];
case AtlasRenderType::r8PixelLocalStorageEXT:
#ifdef RIVE_ANDROID
if (capabilities.EXT_shader_pixel_local_storage)
{
return AtlasRenderType::r8PixelLocalStorageEXT;
}
#endif
[[fallthrough]];
case AtlasRenderType::r32uiPixelLocalStorageANGLE:
#ifndef RIVE_ANDROID
if (capabilities.ANGLE_shader_pixel_local_storage_coherent)
{
return AtlasRenderType::r32uiPixelLocalStorageANGLE;
}
#endif
[[fallthrough]];
case AtlasRenderType::r32iAtomicTexture:
#ifndef RIVE_WEBGL
if (capabilities.ARB_shader_image_load_store ||
capabilities.OES_shader_image_atomic)
{
return AtlasRenderType::r32iAtomicTexture;
}
#endif
[[fallthrough]];
case AtlasRenderType::rgba8:
return AtlasRenderType::rgba8;
}
RIVE_UNREACHABLE();
}
RenderContextGLImpl::RenderContextGLImpl(
const char* rendererString,
GLCapabilities capabilities,
std::unique_ptr<PixelLocalStorageImpl> plsImpl,
ShaderCompilationMode shaderCompilationMode) :
m_capabilities(capabilities),
m_plsImpl(std::move(plsImpl)),
m_atlasRenderType(select_atlas_render_type(m_capabilities)),
m_pipelineManager(shaderCompilationMode, this),
m_state(make_rcp<GLState>(m_capabilities))
{
if (m_capabilities.isANGLESystemDriver &&
capabilities.KHR_blend_equation_advanced)
{
// Some ANGLE devices report support for this extension but render
// incorrectly with it, so we'll need to run a quick test to validate
// that we get the proper color out of doing advance blending before
// rendering with it.
m_testForAdvancedBlendError = true;
}
if (m_plsImpl != nullptr)
{
m_plsImpl->getSupportedInterlockModes(m_capabilities,
&m_platformFeatures);
}
if (m_capabilities.KHR_blend_equation_advanced ||
m_capabilities.KHR_blend_equation_advanced_coherent)
{
m_platformFeatures.supportsBlendAdvancedKHR = true;
}
if (m_capabilities.KHR_blend_equation_advanced_coherent)
{
m_platformFeatures.supportsBlendAdvancedCoherentKHR = true;
}
if (m_capabilities.EXT_clip_cull_distance)
{
m_platformFeatures.supportsClipPlanes = true;
}
if (strstr(rendererString, "Apple") && strstr(rendererString, "Metal"))
{
// In Metal, non-flat varyings preserve their exact value if all
// vertices in the triangle emit the same value, and we also see a small
// (5-10%) improvement from not using flat varyings.
m_platformFeatures.avoidFlatVaryings = true;
}
if (m_capabilities.isPowerVR || strstr(rendererString, "Mali-G52"))
{
// PowerVR (Vivo Y21, Rogue GE8320; OpenGL ES 3.2 build 1.13@5776728a)
// and Mali-G52 (Panfrost, e.g. MediaTek MT8169) hit a reset condition
// that corrupts pixel local storage when rendering a complex feather
// directly into PLS. Route feathers through the offscreen atlas on
// these GPUs.
m_platformFeatures.alwaysFeatherToAtlas = true;
}
m_platformFeatures.clipSpaceBottomUp = true;
m_platformFeatures.framebufferBottomUp = true;
GLint maxTextureSize;
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize);
m_platformFeatures.maxTextureSize = maxTextureSize;
m_platformFeatures.supportsTextureCompressionBC =
m_capabilities.EXT_texture_compression_s3tc &&
m_capabilities.EXT_texture_compression_bptc;
m_platformFeatures.supportsTextureCompressionASTC =
m_capabilities.KHR_texture_compression_astc_ldr;
m_platformFeatures.supportsTextureCompressionETC2 =
m_capabilities.supportsETC2;
std::vector<const char*> generalDefines;
if (!m_capabilities.ARB_shader_storage_buffer_object)
{
generalDefines.push_back(GLSL_DISABLE_SHADER_STORAGE_BUFFERS);
}
const char* colorRampSources[] = {glsl::constants,
glsl::flush_uniforms,
glsl::common,
glsl::color_ramp};
m_colorRampProgram.compileAndAttachShader(GL_VERTEX_SHADER,
generalDefines.data(),
generalDefines.size(),
colorRampSources,
std::size(colorRampSources),
m_capabilities);
m_colorRampProgram.compileAndAttachShader(GL_FRAGMENT_SHADER,
generalDefines.data(),
generalDefines.size(),
colorRampSources,
std::size(colorRampSources),
m_capabilities);
m_colorRampProgram.link();
glUniformBlockBinding(
m_colorRampProgram,
glGetUniformBlockIndex(m_colorRampProgram, GLSL_FlushUniforms),
FLUSH_UNIFORM_BUFFER_IDX);
m_state->bindVAO(m_colorRampVAO);
glEnableVertexAttribArray(0);
glVertexAttribDivisor(0, 1);
// Emulate the feather texture1d array as a texture2d since GLES doesn't
// have texture1d.
glActiveTexture(GL_TEXTURE0 + FEATHER_TEXTURE_IDX);
glBindTexture(GL_TEXTURE_2D, m_featherTexture);
glTexStorage2D(GL_TEXTURE_2D,
1,
GL_R16F,
gpu::GAUSSIAN_TABLE_SIZE,
FEATHER_TEXTURE_1D_ARRAY_LENGTH);
m_state->bindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
glTexSubImage2D(GL_TEXTURE_2D,
0,
0,
FEATHER_FUNCTION_ARRAY_INDEX,
gpu::GAUSSIAN_TABLE_SIZE,
1,
GL_RED,
GL_HALF_FLOAT,
gpu::g_gaussianIntegralTableF16);
glTexSubImage2D(GL_TEXTURE_2D,
0,
0,
FEATHER_INVERSE_FUNCTION_ARRAY_INDEX,
gpu::GAUSSIAN_TABLE_SIZE,
1,
GL_RED,
GL_HALF_FLOAT,
gpu::g_inverseGaussianIntegralTableF16);
const GLenum featherTextureFilter =
m_capabilities.OES_texture_half_float_linear ? GL_LINEAR : GL_NEAREST;
glutils::SetTexture2DSamplingParams(featherTextureFilter,
featherTextureFilter);
const char* tessellateSources[] = {glsl::constants,
glsl::flush_uniforms,
glsl::common,
glsl::bezier_utils,
glsl::tessellate};
m_tessellateProgram.compileAndAttachShader(GL_VERTEX_SHADER,
generalDefines.data(),
generalDefines.size(),
tessellateSources,
std::size(tessellateSources),
m_capabilities);
m_tessellateProgram.compileAndAttachShader(GL_FRAGMENT_SHADER,
generalDefines.data(),
generalDefines.size(),
tessellateSources,
std::size(tessellateSources),
m_capabilities);
m_tessellateProgram.link();
m_state->bindProgram(m_tessellateProgram);
glutils::Uniform1iByName(m_tessellateProgram,
GLSL_featherTexture,
FEATHER_TEXTURE_IDX);
glUniformBlockBinding(
m_tessellateProgram,
glGetUniformBlockIndex(m_tessellateProgram, GLSL_FlushUniforms),
FLUSH_UNIFORM_BUFFER_IDX);
if (!m_capabilities.ARB_shader_storage_buffer_object)
{
// Our GL driver doesn't support storage buffers. We polyfill these
// buffers as textures.
glutils::Uniform1iByName(m_tessellateProgram,
GLSL_pathBuffer,
PATH_BUFFER_IDX);
glutils::Uniform1iByName(m_tessellateProgram,
GLSL_contourBuffer,
CONTOUR_BUFFER_IDX);
}
m_state->bindVAO(m_tessellateVAO);
for (int i = 0; i < 4; ++i)
{
glEnableVertexAttribArray(i);
// Draw two instances per TessVertexSpan: one normal and one optional
// reflection.
glVertexAttribDivisor(i, 1);
}
m_state->bindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_tessSpanIndexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,
sizeof(gpu::kTessSpanIndices),
gpu::kTessSpanIndices,
GL_STATIC_DRAW);
m_state->bindVAO(m_drawVAO);
PatchVertex patchVertices[kPatchVertexBufferCount];
uint16_t patchIndices[kPatchIndexBufferCount];
GeneratePatchBufferData(patchVertices, patchIndices);
m_state->bindBuffer(GL_ARRAY_BUFFER, m_patchVerticesBuffer);
glBufferData(GL_ARRAY_BUFFER,
sizeof(patchVertices),
patchVertices,
GL_STATIC_DRAW);
m_state->bindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_patchIndicesBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,
sizeof(patchIndices),
patchIndices,
GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0,
4,
GL_FLOAT,
GL_FALSE,
sizeof(PatchVertex),
nullptr);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1,
4,
GL_FLOAT,
GL_FALSE,
sizeof(PatchVertex),
reinterpret_cast<const void*>(sizeof(float) * 4));
m_state->bindVAO(m_trianglesVAO);
glEnableVertexAttribArray(0);
// We draw imageRects when in atomic mode.
m_state->bindVAO(m_imageRectVAO);
m_state->bindBuffer(GL_ARRAY_BUFFER, m_imageRectVertexBuffer);
glBufferData(GL_ARRAY_BUFFER,
sizeof(gpu::kImageRectVertices),
gpu::kImageRectVertices,
GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0,
4,
GL_FLOAT,
GL_FALSE,
sizeof(gpu::ImageRectVertex),
nullptr);
m_state->bindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_imageRectIndexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,
sizeof(gpu::kImageRectIndices),
gpu::kImageRectIndices,
GL_STATIC_DRAW);
m_state->bindVAO(m_imageMeshVAO);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
if (m_plsImpl != nullptr)
{
m_plsImpl->init(m_state);
}
}
RenderContextGLImpl::~RenderContextGLImpl()
{
glDeleteTextures(1, &m_gradientTexture);
glDeleteTextures(1, &m_tessVertexTexture);
// Because glutils wrappers delete GL objects that might affect bindings.
m_state->invalidate();
}
// Indicates that the atlas needs a fullscreen draw at the end, in order to
// resolve it into a GL_R8 texture that can be sampled.
constexpr static bool needs_atlas_resolve_draw(
RenderContextGLImpl::AtlasRenderType atlasRenderType)
{
switch (atlasRenderType)
{
using AtlasRenderType = RenderContextGLImpl::AtlasRenderType;
case AtlasRenderType::r16f:
case AtlasRenderType::r32f:
return false;
case AtlasRenderType::r32uiFramebufferFetch:
case AtlasRenderType::r8PixelLocalStorageEXT:
case AtlasRenderType::r32uiPixelLocalStorageANGLE:
case AtlasRenderType::r32iAtomicTexture:
case AtlasRenderType::rgba8:
return true;
}
RIVE_UNREACHABLE();
}
void RenderContextGLImpl::buildAtlasRenderPipelines()
{
std::vector<const char*> defines;
defines.push_back(GLSL_DRAW_PATH);
defines.push_back(GLSL_ENABLE_FEATHER);
defines.push_back(GLSL_ENABLE_INSTANCE_INDEX);
if (!m_capabilities.ARB_shader_storage_buffer_object)
{
defines.push_back(GLSL_DISABLE_SHADER_STORAGE_BUFFERS);
}
m_atlasFillPipelineState = gpu::ATLAS_FILL_PIPELINE_STATE;
m_atlasStrokePipelineState = gpu::ATLAS_STROKE_PIPELINE_STATE;
switch (m_atlasRenderType)
{
case AtlasRenderType::r16f:
case AtlasRenderType::r32f:
break;
case AtlasRenderType::r32uiFramebufferFetch:
defines.push_back(GLSL_ATLAS_RENDER_TARGET_R32UI_FRAMEBUFFER_FETCH);
m_atlasFillPipelineState.blendEquation = gpu::BlendEquation::none;
m_atlasStrokePipelineState.blendEquation = gpu::BlendEquation::none;
break;
case AtlasRenderType::r8PixelLocalStorageEXT:
#ifdef RIVE_ANDROID
defines.push_back(GLSL_ATLAS_RENDER_TARGET_R8_PLS_EXT);
m_atlasFillPipelineState.blendEquation = gpu::BlendEquation::none;
m_atlasStrokePipelineState.blendEquation = gpu::BlendEquation::none;
#else
RIVE_UNREACHABLE();
#endif
break;
case AtlasRenderType::r32uiPixelLocalStorageANGLE:
#ifndef RIVE_ANDROID
defines.push_back(GLSL_ATLAS_RENDER_TARGET_R32UI_PLS_ANGLE);
m_atlasFillPipelineState.blendEquation = gpu::BlendEquation::none;
m_atlasStrokePipelineState.blendEquation = gpu::BlendEquation::none;
#else
RIVE_UNREACHABLE();
#endif
break;
case AtlasRenderType::r32iAtomicTexture:
#ifndef RIVE_WEBGL
defines.push_back(GLSL_ATLAS_RENDER_TARGET_R32I_ATOMIC_TEXTURE);
m_atlasFillPipelineState.colorWriteEnabled = false;
m_atlasFillPipelineState.blendEquation = gpu::BlendEquation::none;
m_atlasStrokePipelineState.colorWriteEnabled = false;
m_atlasStrokePipelineState.blendEquation = gpu::BlendEquation::none;
#else
RIVE_UNREACHABLE();
#endif
break;
case AtlasRenderType::rgba8:
defines.push_back(GLSL_ATLAS_RENDER_TARGET_RGBA8_UNORM);
break;
}
const char* atlasSources[] = {glsl::constants,
glsl::flush_uniforms,
glsl::common,
glsl::draw_path_common,
glsl::render_atlas};
m_atlasVertexShader.compile(GL_VERTEX_SHADER,
defines.data(),
defines.size(),
atlasSources,
std::size(atlasSources),
m_capabilities);
defines.push_back(GLSL_ATLAS_FEATHERED_FILL);
m_atlasFillProgram.compile(m_atlasVertexShader,
defines.data(),
defines.size(),
atlasSources,
std::size(atlasSources),
m_capabilities,
m_state.get());
defines.pop_back();
defines.push_back(GLSL_ATLAS_FEATHERED_STROKE);
m_atlasStrokeProgram.compile(m_atlasVertexShader,
defines.data(),
defines.size(),
atlasSources,
std::size(atlasSources),
m_capabilities,
m_state.get());
defines.pop_back();
if (needs_atlas_resolve_draw(m_atlasRenderType))
{
// Build the pipelines for clearing and resolving
// EXT_shader_pixel_local_storage.
m_atlasResolveVertexShader.compile(GL_VERTEX_SHADER,
glsl::resolve_atlas,
m_capabilities);
if (m_atlasRenderType == AtlasRenderType::r8PixelLocalStorageEXT)
{
#ifdef RIVE_ANDROID
// EXT_shader_pixel_local_storage doesn't support clearing, so we
// also need to build a program to clear it at the beginning of the
// atlas render pass.
const char* atlasClearDefines[] = {
GLSL_ATLAS_RENDER_TARGET_R8_PLS_EXT,
GLSL_CLEAR_COVERAGE};
const char* atlasClearSources[] = {glsl::resolve_atlas};
m_atlasClearProgram = glutils::Program();
glAttachShader(m_atlasClearProgram, m_atlasResolveVertexShader);
m_atlasClearProgram.compileAndAttachShader(
GL_FRAGMENT_SHADER,
atlasClearDefines,
std::size(atlasClearDefines),
atlasClearSources,
std::size(atlasClearSources),
m_capabilities);
m_atlasClearProgram.link();
#else
RIVE_UNREACHABLE();
#endif
}
const char* atlasResolveSources[] = {glsl::constants,
glsl::flush_uniforms,
glsl::common,
glsl::resolve_atlas};
m_atlasResolveProgram = glutils::Program();
glAttachShader(m_atlasResolveProgram, m_atlasResolveVertexShader);
m_atlasResolveProgram.compileAndAttachShader(
GL_FRAGMENT_SHADER,
defines.data(),
defines.size(),
atlasResolveSources,
std::size(atlasResolveSources),
m_capabilities);
m_atlasResolveProgram.link();
if (m_atlasRenderType == AtlasRenderType::rgba8)
{
// The "rgba8" resolve shader reads the coverageCount data via
// texelFetch().
m_state->bindProgram(m_atlasResolveProgram);
glutils::Uniform1iByName(m_atlasResolveProgram,
GLSL_atlasRenderTexture,
0);
}
}
}
void RenderContextGLImpl::invalidateGLState()
{
glActiveTexture(GL_TEXTURE0 + TESS_VERTEX_TEXTURE_IDX);
glBindTexture(GL_TEXTURE_2D, m_tessVertexTexture);
glActiveTexture(GL_TEXTURE0 + GRAD_TEXTURE_IDX);
glBindTexture(GL_TEXTURE_2D, m_gradientTexture);
glActiveTexture(GL_TEXTURE0 + FEATHER_TEXTURE_IDX);
glBindTexture(GL_TEXTURE_2D, m_featherTexture);
glActiveTexture(GL_TEXTURE0 + ATLAS_TEXTURE_IDX);
glBindTexture(GL_TEXTURE_2D, m_atlasTexture);
m_state->invalidate();
}
void RenderContextGLImpl::unbindGLInternalResources()
{
m_state->bindVAO(0);
m_state->bindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
m_state->bindBuffer(GL_ARRAY_BUFFER, 0);
m_state->bindBuffer(GL_UNIFORM_BUFFER, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
for (int i = 0; i <= DEFAULT_BINDINGS_SET_SIZE; ++i)
{
glActiveTexture(GL_TEXTURE0 + i);
glBindTexture(GL_TEXTURE_2D, 0);
}
}
rcp<RenderBuffer> RenderContextGLImpl::makeRenderBuffer(RenderBufferType type,
RenderBufferFlags flags,
size_t sizeInBytes)
{
return make_rcp<RenderBufferGLImpl>(type, flags, sizeInBytes, m_state);
}
class TextureGLImpl : public Texture
{
public:
TextureGLImpl(uint32_t width,
uint32_t height,
GLuint textureID,
const GLCapabilities& capabilities) :
Texture(width, height), m_texture(glutils::Texture::Adopt(textureID))
{}
virtual ~TextureGLImpl() = default;
operator GLuint() const { return m_texture; }
void* nativeHandle() const override
{
return reinterpret_cast<void*>(
static_cast<uintptr_t>(static_cast<GLuint>(m_texture)));
}
protected:
glutils::Texture m_texture;
};
#ifdef RIVE_CANVAS
// Lifetime hook for the source texture of a Rive 2D RenderCanvas. When
// this texture is destroyed, the canvas mirror registry entry on the
// owning RenderContextGLImpl must be removed so any subsequent
// wrapRiveTexture lookup for the freed GLuint cannot resurrect a stale
// mirror. The texture's GLuint itself is freed by the base class
// destructor (glutils::Texture RAII).
class CanvasSourceTextureGLImpl : public TextureGLImpl
{
public:
CanvasSourceTextureGLImpl(uint32_t width,
uint32_t height,
GLuint textureID,
const GLCapabilities& caps,
RenderContextGLImpl* owner) :
TextureGLImpl(width, height, textureID, caps),
m_owner(owner),
m_glID(textureID)
{}
~CanvasSourceTextureGLImpl() override
{
if (m_owner != nullptr)
{
m_owner->unregisterCanvasTarget(m_glID);
}
}
private:
RenderContextGLImpl* m_owner;
GLuint m_glID;
};
// Lifetime hook for the mirror texture of an imported canvas. When this
// texture is destroyed, we clear the mirror fields on the registry entry
// (if it still exists) and release the cached read/draw FBOs. The entry
// itself is left in place so the source canvas can re-allocate a new
// mirror later via getOrCreateCanvasMirror.
class CanvasMirrorTextureGLImpl : public TextureGLImpl
{
public:
CanvasMirrorTextureGLImpl(uint32_t width,
uint32_t height,
GLuint textureID,
const GLCapabilities& caps,
RenderContextGLImpl* owner,
GLuint sourceTexID) :
TextureGLImpl(width, height, textureID, caps),
m_owner(owner),
m_sourceTexID(sourceTexID)
{}
~CanvasMirrorTextureGLImpl() override; // Defined below the class
// method definitions on
// RenderContextGLImpl so we
// can call its private API.
private:
RenderContextGLImpl* m_owner;
GLuint m_sourceTexID;
};
#endif // RIVE_CANVAS
rcp<Texture> RenderContextGLImpl::makeImageTexture(uint32_t width,
uint32_t height,
uint32_t mipLevelCount,
GPUTextureFormat format,
const uint8_t imageData[],
uint8_t blockWidth,
uint8_t blockHeight,
[[maybe_unused]] bool srgb,
bool generateRemainingMips)
{
// Pick UNORM internal format. Sampler path treats texels as sRGB-
// encoded bytes (matching the GL_RGBA8 PNG upload).
GLenum sizedInternal;
bool isCompressed = false;
uint32_t bytesPerBlock = 16;
switch (format)
{
case GPUTextureFormat::rgba32:
sizedInternal = GL_RGBA8;
assert(blockWidth == 1 && blockHeight == 1);
bytesPerBlock = 4;
break;
case GPUTextureFormat::bc7:
sizedInternal = 0x8E8C; // GL_COMPRESSED_RGBA_BPTC_UNORM
isCompressed = true;
break;
case GPUTextureFormat::etc2:
sizedInternal = 0x9278; // GL_COMPRESSED_RGBA8_ETC2_EAC
isCompressed = true;
break;
case GPUTextureFormat::astc:
{
const int idx = rive::astcFootprintIndex(blockWidth, blockHeight);
if (idx < 0)
{
assert(!"unsupported ASTC block footprint");
return nullptr;
}
// KHR_texture_compression_astc_ldr lays the per-footprint enums
// out contiguously starting at GL_COMPRESSED_RGBA_ASTC_4x4_KHR, in
// the same canonical order as astcFootprintIndex().
sizedInternal =
static_cast<GLenum>(GL_COMPRESSED_RGBA_ASTC_4x4_KHR + idx);
isCompressed = true;
break;
}
default:
assert(!"unsupported format");
return nullptr;
}
assert(!(generateRemainingMips && isCompressed) &&
"glGenerateMipmap is undefined on compressed textures");
GLuint textureID;
glGenTextures(1, &textureID);
glActiveTexture(GL_TEXTURE0 + IMAGE_TEXTURE_IDX);
glBindTexture(GL_TEXTURE_2D, textureID);
glTexStorage2D(GL_TEXTURE_2D,
static_cast<GLsizei>(mipLevelCount),
sizedInternal,
width,
height);
if (imageData != nullptr)
{
// When the caller wants the GPU to auto-fill mips 1..N from mip 0
// (PNG path), only upload level 0 and finish via glGenerateMipmap.
const uint32_t levelsToUpload =
generateRemainingMips ? 1u : mipLevelCount;
size_t srcOffset = 0;
for (uint32_t i = 0; i < levelsToUpload; ++i)
{
const uint32_t logW = std::max<uint32_t>(1u, width >> i);
const uint32_t logH = std::max<uint32_t>(1u, height >> i);
const uint32_t blocksX = (logW + blockWidth - 1) / blockWidth;
const uint32_t blocksY = (logH + blockHeight - 1) / blockHeight;
const size_t levelBytes =
static_cast<size_t>(blocksX) * blocksY * bytesPerBlock;
if (isCompressed)
{
glCompressedTexSubImage2D(GL_TEXTURE_2D,
static_cast<GLint>(i),
0,
0,
logW,
logH,
sizedInternal,
static_cast<GLsizei>(levelBytes),
imageData + srcOffset);
}
else
{
glTexSubImage2D(GL_TEXTURE_2D,
static_cast<GLint>(i),
0,
0,
logW,
logH,
GL_RGBA,
GL_UNSIGNED_BYTE,
imageData + srcOffset);
}
srcOffset += levelBytes;
}
if (generateRemainingMips && mipLevelCount > 1)
{
glGenerateMipmap(GL_TEXTURE_2D);
}
}
return adoptImageTexture(width, height, textureID);
}
rcp<Texture> RenderContextGLImpl::adoptImageTexture(uint32_t width,
uint32_t height,
GLuint textureID)
{
return make_rcp<TextureGLImpl>(width, height, textureID, m_capabilities);
}
#ifdef RIVE_CANVAS
rcp<RenderCanvas> RenderContextGLImpl::makeRenderCanvas(uint32_t width,
uint32_t height)
{
GLuint tex;
glGenTextures(1, &tex);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, width, height);
// Wrap as a CanvasSourceTextureGLImpl so the registry entry is
// unregistered automatically when the source texture is destroyed.
// The texture takes ownership of `tex` (RAII via glutils::Texture).
auto sourceTexture =
rcp<TextureGLImpl>(new CanvasSourceTextureGLImpl(width,
height,
tex,
m_capabilities,
this));
auto renderImage = make_rcp<RiveRenderImage>(std::move(sourceTexture));
// Wrap as TextureRenderTargetGL. It references the same GLuint without
// taking ownership.
auto renderTarget = make_rcp<TextureRenderTargetGL>(width, height);
renderTarget->setTargetTexture(tex);
// GL renders into the canvas with row 0 = visual bottom (framebuffer
// bottom-up convention). Register the source GLuint with the mirror
// registry so wrapRiveTexture (ore_context_gl.cpp) can detect it
// later and allocate a Y-flipped companion when an Ore pipeline
// imports it as a sampled texture. The registration is bookkeeping
// only — no GPU allocation happens until first import.
// See dev/ore_canvas_import_invariant.md.
registerCanvasTarget(tex);
return make_rcp<RenderCanvas>(std::move(renderImage),
std::move(renderTarget));
}
std::unique_ptr<rive::ore::Context> RenderContextGLImpl::makeOreContext()
{
return rive::ore::ContextGL::Make();
}
// ────────────────────────────────────────────────────────────────────────────
// Canvas mirror registry implementation (GL-only "imported canvas" handling)
// ────────────────────────────────────────────────────────────────────────────
rcp<RiveRenderImage> RenderContextGLImpl::getCanvasImportMirror(
gpu::Texture* sourceTex,
uint32_t width,
uint32_t height)
{
if (sourceTex == nullptr)
{
return nullptr;
}
GLuint glID = static_cast<GLuint>(
reinterpret_cast<uintptr_t>(sourceTex->nativeHandle()));
if (glID == 0)
{
return nullptr;
}
return getOrCreateCanvasMirror(glID, width, height);
}
void RenderContextGLImpl::registerCanvasTarget(GLuint sourceTex)
{
// Insert an empty entry. mirrorTex stays 0 / hasMirror stays false
// until the first wrapRiveTexture call for this source.
m_canvasMirrors[sourceTex] = RenderContextGLImpl::CanvasMirrorEntry{};
}
void RenderContextGLImpl::unregisterCanvasTarget(GLuint sourceTex)
{
auto it = m_canvasMirrors.find(sourceTex);
if (it == m_canvasMirrors.end())
{
return;
}
// Free FBOs if a mirror was ever allocated. The mirror texture itself
// is owned by its CanvasMirrorTextureGLImpl wrapper; that wrapper is
// either still alive (in which case its destructor will be a no-op
// when it tries to remove an already-removed entry) or already dead
// (in which case the FBOs have already been cleared and re-clearing
// is harmless).
if (it->second.readFBO != 0)
{
glDeleteFramebuffers(1, &it->second.readFBO);
}
if (it->second.drawFBO != 0)
{
glDeleteFramebuffers(1, &it->second.drawFBO);
}
m_canvasMirrors.erase(it);
}
rcp<RiveRenderImage> RenderContextGLImpl::getOrCreateCanvasMirror(
GLuint sourceTex,
uint32_t width,
uint32_t height)
{
auto it = m_canvasMirrors.find(sourceTex);
if (it == m_canvasMirrors.end())
{
// Not a registered canvas target — caller should fall through
// and use the source texture directly.
return nullptr;
}
RenderContextGLImpl::CanvasMirrorEntry& entry = it->second;
// If a mirror already exists, the caller should be reusing the
// RiveRenderImage they previously got back from us. We don't keep
// a strong ref to the mirror image (only the wrapping texture
// implementation), so re-creating one here would alias a live
// GLuint and double-free on shutdown. Therefore: if hasMirror is
// true, we MUST NOT allocate again. Return null and let the caller
// sample the source directly as a fallback. In practice this code
// path is unreachable — the Lua binding caches its cachedOreView
// after the first :view() call.
if (entry.hasMirror)
{
return nullptr;
}
// Allocate a new companion texture sized to match the source.
GLuint mirrorTex;
glGenTextures(1, &mirrorTex);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, mirrorTex);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, width, height);
// Allocate persistent read/draw FBOs and attach source/mirror.
glGenFramebuffers(1, &entry.readFBO);
glGenFramebuffers(1, &entry.drawFBO);
glBindFramebuffer(GL_READ_FRAMEBUFFER, entry.readFBO);
glFramebufferTexture2D(GL_READ_FRAMEBUFFER,
GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D,
sourceTex,
0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, entry.drawFBO);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER,
GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D,
mirrorTex,
0);
glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
entry.mirrorTex = mirrorTex;
entry.width = width;
entry.height = height;
entry.hasMirror = true;
// Wrap the mirror as a CanvasMirrorTextureGLImpl so its destructor
// can clear the entry's mirror fields when the wrapping
// RiveRenderImage is dropped (e.g. when the Lua script GCs the
// bind group containing the view).
auto mirrorTexture =
rcp<TextureGLImpl>(new CanvasMirrorTextureGLImpl(width,
height,
mirrorTex,
m_capabilities,
this,
sourceTex));
auto mirrorImage = make_rcp<RiveRenderImage>(std::move(mirrorTexture));
// The constructor mutated GL FBO/texture bindings; invalidate
// Rive's GLState cache so subsequent rendering re-applies state.
m_state->invalidate();