/
WebGLRenderingContextBase.cpp
5935 lines (5285 loc) · 222 KB
/
WebGLRenderingContextBase.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2015-2021 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebGLRenderingContextBase.h"
#if ENABLE(WEBGL)
#include "ANGLEInstancedArrays.h"
#include "CachedImage.h"
#include "DOMWindow.h"
#include "DiagnosticLoggingClient.h"
#include "DiagnosticLoggingKeys.h"
#include "Document.h"
#include "EXTBlendMinMax.h"
#include "EXTColorBufferFloat.h"
#include "EXTColorBufferHalfFloat.h"
#include "EXTFloatBlend.h"
#include "EXTFragDepth.h"
#include "EXTShaderTextureLOD.h"
#include "EXTTextureCompressionBPTC.h"
#include "EXTTextureCompressionRGTC.h"
#include "EXTTextureFilterAnisotropic.h"
#include "EXTTextureNorm16.h"
#include "EXTsRGB.h"
#include "EventNames.h"
#include "Frame.h"
#include "FrameLoader.h"
#include "FrameLoaderClient.h"
#include "FrameView.h"
#include "GraphicsContext.h"
#include "GraphicsContextGLImageExtractor.h"
#include "GraphicsLayerContentsDisplayDelegate.h"
#include "HTMLCanvasElement.h"
#include "HTMLImageElement.h"
#include "HTMLVideoElement.h"
#include "HostWindow.h"
#include "ImageBitmap.h"
#include "ImageBuffer.h"
#include "ImageData.h"
#include "InspectorInstrumentation.h"
#include "IntSize.h"
#include "JSExecState.h"
#include "KHRParallelShaderCompile.h"
#include "Logging.h"
#include "NavigatorWebXR.h"
#include "NotImplemented.h"
#include "OESDrawBuffersIndexed.h"
#include "OESElementIndexUint.h"
#include "OESFBORenderMipmap.h"
#include "OESStandardDerivatives.h"
#include "OESTextureFloat.h"
#include "OESTextureFloatLinear.h"
#include "OESTextureHalfFloat.h"
#include "OESTextureHalfFloatLinear.h"
#include "OESVertexArrayObject.h"
#include "Page.h"
#include "RenderBox.h"
#include "Settings.h"
#include "WebCoreOpaqueRoot.h"
#include "WebGL2RenderingContext.h"
#include "WebGLActiveInfo.h"
#include "WebGLBuffer.h"
#include "WebGLColorBufferFloat.h"
#include "WebGLCompressedTextureASTC.h"
#include "WebGLCompressedTextureETC.h"
#include "WebGLCompressedTextureETC1.h"
#include "WebGLCompressedTexturePVRTC.h"
#include "WebGLCompressedTextureS3TC.h"
#include "WebGLCompressedTextureS3TCsRGB.h"
#include "WebGLContextAttributes.h"
#include "WebGLContextEvent.h"
#include "WebGLContextGroup.h"
#include "WebGLDebugRendererInfo.h"
#include "WebGLDebugShaders.h"
#include "WebGLDepthTexture.h"
#include "WebGLDrawBuffers.h"
#include "WebGLDrawInstancedBaseVertexBaseInstance.h"
#include "WebGLFramebuffer.h"
#include "WebGLLoseContext.h"
#include "WebGLMultiDraw.h"
#include "WebGLMultiDrawInstancedBaseVertexBaseInstance.h"
#include "WebGLProgram.h"
#include "WebGLProvokingVertex.h"
#include "WebGLRenderbuffer.h"
#include "WebGLRenderingContext.h"
#include "WebGLSampler.h"
#include "WebGLShader.h"
#include "WebGLShaderPrecisionFormat.h"
#include "WebGLTexture.h"
#include "WebGLTransformFeedback.h"
#include "WebGLUniformLocation.h"
#include "WebGLVertexArrayObject.h"
#include "WebGLVertexArrayObjectOES.h"
#include "WebXRSystem.h"
#include "WorkerClient.h"
#include "WorkerGlobalScope.h"
#include <JavaScriptCore/ConsoleMessage.h>
#include <JavaScriptCore/JSCInlines.h>
#include <JavaScriptCore/ScriptCallStack.h>
#include <JavaScriptCore/ScriptCallStackFactory.h>
#include <JavaScriptCore/SlotVisitor.h>
#include <JavaScriptCore/SlotVisitorInlines.h>
#include <JavaScriptCore/TypedArrayInlines.h>
#include <JavaScriptCore/Uint32Array.h>
#include <wtf/CheckedArithmetic.h>
#include <wtf/HashMap.h>
#include <wtf/HexNumber.h>
#include <wtf/IsoMallocInlines.h>
#include <wtf/Lock.h>
#include <wtf/Locker.h>
#include <wtf/MainThread.h>
#include <wtf/NeverDestroyed.h>
#include <wtf/Scope.h>
#include <wtf/StdLibExtras.h>
#include <wtf/ThreadSpecific.h>
#include <wtf/UniqueArray.h>
#include <wtf/text/CString.h>
#include <wtf/text/StringBuilder.h>
#if ENABLE(OFFSCREEN_CANVAS)
#include "OffscreenCanvas.h"
#endif
#if PLATFORM(MAC)
#include "PlatformScreen.h"
#endif
namespace WebCore {
WTF_MAKE_ISO_ALLOCATED_IMPL(WebGLRenderingContextBase);
static constexpr Seconds secondsBetweenRestoreAttempts { 1_s };
static constexpr int maxGLErrorsAllowedToConsole = 256;
static constexpr Seconds checkContextLossHandlingDelay { 3_s };
static constexpr size_t maxActiveContexts = 16;
static constexpr size_t maxActiveWorkerContexts = 4;
namespace {
GCGLint clamp(GCGLint value, GCGLint min, GCGLint max)
{
if (value < min)
value = min;
if (value > max)
value = max;
return value;
}
// Return true if a character belongs to the ASCII subset as defined in
// GLSL ES 1.0 spec section 3.1.
bool validateCharacter(unsigned char c)
{
// Printing characters are valid except " $ ` @ \ ' DEL.
if (c >= 32 && c <= 126
&& c != '"' && c != '$' && c != '`' && c != '@' && c != '\\' && c != '\'')
return true;
// Horizontal tab, line feed, vertical tab, form feed, carriage return
// are also valid.
if (c >= 9 && c <= 13)
return true;
return false;
}
bool isPrefixReserved(const String& name)
{
if (name.startsWith("gl_"_s) || name.startsWith("webgl_"_s) || name.startsWith("_webgl_"_s))
return true;
return false;
}
// ES2 formats and internal formats supported by TexImageSource.
static const GCGLenum SupportedFormatsES2[] = {
GraphicsContextGL::RGB,
GraphicsContextGL::RGBA,
GraphicsContextGL::LUMINANCE_ALPHA,
GraphicsContextGL::LUMINANCE,
GraphicsContextGL::ALPHA,
};
// ES2 types supported by TexImageSource.
static const GCGLenum SupportedTypesES2[] = {
GraphicsContextGL::UNSIGNED_BYTE,
GraphicsContextGL::UNSIGNED_SHORT_5_6_5,
GraphicsContextGL::UNSIGNED_SHORT_4_4_4_4,
GraphicsContextGL::UNSIGNED_SHORT_5_5_5_1,
};
// ES3 internal formats supported by TexImageSource.
static const GCGLenum SupportedInternalFormatsTexImageSourceES3[] = {
GraphicsContextGL::R8,
GraphicsContextGL::R16F,
GraphicsContextGL::R32F,
GraphicsContextGL::R8UI,
GraphicsContextGL::RG8,
GraphicsContextGL::RG16F,
GraphicsContextGL::RG32F,
GraphicsContextGL::RG8UI,
GraphicsContextGL::RGB8,
GraphicsContextGL::SRGB8,
GraphicsContextGL::RGB565,
GraphicsContextGL::R11F_G11F_B10F,
GraphicsContextGL::RGB9_E5,
GraphicsContextGL::RGB16F,
GraphicsContextGL::RGB32F,
GraphicsContextGL::RGB8UI,
GraphicsContextGL::RGBA8,
GraphicsContextGL::SRGB8_ALPHA8,
GraphicsContextGL::RGB5_A1,
GraphicsContextGL::RGBA4,
GraphicsContextGL::RGBA16F,
GraphicsContextGL::RGBA32F,
GraphicsContextGL::RGBA8UI,
GraphicsContextGL::RGB10_A2,
};
// ES3 formats supported by TexImageSource.
static const GCGLenum SupportedFormatsTexImageSourceES3[] = {
GraphicsContextGL::RED,
GraphicsContextGL::RED_INTEGER,
GraphicsContextGL::RG,
GraphicsContextGL::RG_INTEGER,
GraphicsContextGL::RGB,
GraphicsContextGL::RGB_INTEGER,
GraphicsContextGL::RGBA,
GraphicsContextGL::RGBA_INTEGER,
};
// ES3 types supported by TexImageSource.
static const GCGLenum SupportedTypesTexImageSourceES3[] = {
GraphicsContextGL::HALF_FLOAT,
GraphicsContextGL::FLOAT,
GraphicsContextGL::UNSIGNED_INT_10F_11F_11F_REV,
GraphicsContextGL::UNSIGNED_INT_2_10_10_10_REV,
};
// Internal formats exposed by GL_EXT_sRGB.
static const GCGLenum SupportedInternalFormatsEXTsRGB[] = {
GraphicsContextGL::SRGB,
GraphicsContextGL::SRGB_ALPHA,
};
// Formats exposed by GL_EXT_sRGB.
static const GCGLenum SupportedFormatsEXTsRGB[] = {
GraphicsContextGL::SRGB,
GraphicsContextGL::SRGB_ALPHA,
};
// Types exposed by GL_OES_texture_float.
static const GCGLenum SupportedTypesOESTextureFloat[] = {
GraphicsContextGL::FLOAT,
};
// Types exposed by GL_OES_texture_half_float.
static const GCGLenum SupportedTypesOESTextureHalfFloat[] = {
GraphicsContextGL::HALF_FLOAT_OES,
};
} // namespace anonymous
class ScopedUnpackParametersResetRestore {
public:
explicit ScopedUnpackParametersResetRestore(WebGLRenderingContextBase* context, bool enabled = true)
: m_context(context), m_enabled(enabled)
{
if (m_enabled)
m_context->resetUnpackParameters();
}
~ScopedUnpackParametersResetRestore()
{
if (m_enabled)
m_context->restoreUnpackParameters();
}
private:
WebGLRenderingContextBase* m_context;
bool m_enabled;
};
class ScopedDisableRasterizerDiscard {
public:
explicit ScopedDisableRasterizerDiscard(WebGLRenderingContextBase* context, bool wasEnabled)
: m_context(context)
, m_wasEnabled(wasEnabled)
{
if (m_wasEnabled)
m_context->disable(GraphicsContextGL::RASTERIZER_DISCARD);
}
~ScopedDisableRasterizerDiscard()
{
if (m_wasEnabled)
m_context->enable(GraphicsContextGL::RASTERIZER_DISCARD);
}
private:
WebGLRenderingContextBase* m_context;
bool m_wasEnabled;
};
class ScopedEnableBackbuffer {
public:
explicit ScopedEnableBackbuffer(GraphicsContextGL& context, GCGLenum backDrawBuffer, bool isWebGL2)
: m_context(context)
, m_backDrawBufferDisabled(backDrawBuffer == GraphicsContextGL::NONE)
, m_isWebGL2(isWebGL2)
{
ASSERT(backDrawBuffer == GraphicsContextGL::NONE || backDrawBuffer == GraphicsContextGL::BACK);
if (m_backDrawBufferDisabled) {
GCGLenum value[1] { GraphicsContextGL::COLOR_ATTACHMENT0 };
if (m_isWebGL2)
m_context.drawBuffers(value);
else
m_context.drawBuffersEXT(value);
}
}
~ScopedEnableBackbuffer()
{
if (m_backDrawBufferDisabled) {
GCGLenum value[1] { GraphicsContextGL::NONE };
if (m_isWebGL2)
m_context.drawBuffers(value);
else
m_context.drawBuffersEXT(value);
}
}
private:
GraphicsContextGL& m_context;
const bool m_backDrawBufferDisabled;
const bool m_isWebGL2;
};
#define ADD_VALUES_TO_SET(set, arr) \
set.add(arr, arr + WTF_ARRAY_LENGTH(arr))
InspectorScopedShaderProgramHighlight::InspectorScopedShaderProgramHighlight(WebGLRenderingContextBase& context, WebGLProgram* program)
: m_context(context)
, m_program(program)
{
showHighlight();
}
InspectorScopedShaderProgramHighlight::~InspectorScopedShaderProgramHighlight()
{
hideHighlight();
}
void InspectorScopedShaderProgramHighlight::showHighlight()
{
if (!m_program || LIKELY(!InspectorInstrumentation::isWebGLProgramHighlighted(m_context, *m_program)))
return;
if (m_context.m_framebufferBinding)
return;
auto& gl = *m_context.graphicsContextGL();
// When OES_draw_buffers_indexed extension is enabled,
// these state queries return the state for draw buffer 0.
// Constant blend color is always the same for all draw buffers.
gl.getFloatv(GraphicsContextGL::BLEND_COLOR, m_savedBlend.color);
m_savedBlend.equationRGB = gl.getInteger(GraphicsContextGL::BLEND_EQUATION_RGB);
m_savedBlend.equationAlpha = gl.getInteger(GraphicsContextGL::BLEND_EQUATION_ALPHA);
m_savedBlend.srcRGB = gl.getInteger(GraphicsContextGL::BLEND_SRC_RGB);
m_savedBlend.dstRGB = gl.getInteger(GraphicsContextGL::BLEND_DST_RGB);
m_savedBlend.srcAlpha = gl.getInteger(GraphicsContextGL::BLEND_SRC_ALPHA);
m_savedBlend.dstAlpha = gl.getInteger(GraphicsContextGL::BLEND_DST_ALPHA);
m_savedBlend.enabled = gl.isEnabled(GraphicsContextGL::BLEND);
static const GCGLfloat red = 111.0 / 255.0;
static const GCGLfloat green = 168.0 / 255.0;
static const GCGLfloat blue = 220.0 / 255.0;
static const GCGLfloat alpha = 2.0 / 3.0;
gl.blendColor(red, green, blue, alpha);
if (m_context.m_oesDrawBuffersIndexed) {
gl.enableiOES(GraphicsContextGL::BLEND, 0);
gl.blendEquationiOES(0, GraphicsContextGL::FUNC_ADD);
gl.blendFunciOES(0, GraphicsContextGL::CONSTANT_COLOR, GraphicsContextGL::ONE_MINUS_SRC_ALPHA);
} else {
gl.enable(GraphicsContextGL::BLEND);
gl.blendEquation(GraphicsContextGL::FUNC_ADD);
gl.blendFunc(GraphicsContextGL::CONSTANT_COLOR, GraphicsContextGL::ONE_MINUS_SRC_ALPHA);
}
m_didApply = true;
}
void InspectorScopedShaderProgramHighlight::hideHighlight()
{
if (!m_didApply)
return;
auto& gl = *m_context.graphicsContextGL();
gl.blendColor(m_savedBlend.color[0], m_savedBlend.color[1], m_savedBlend.color[2], m_savedBlend.color[3]);
if (m_context.m_oesDrawBuffersIndexed) {
gl.blendEquationSeparateiOES(0, m_savedBlend.equationRGB, m_savedBlend.equationAlpha);
gl.blendFuncSeparateiOES(0, m_savedBlend.srcRGB, m_savedBlend.dstRGB, m_savedBlend.srcAlpha, m_savedBlend.dstAlpha);
if (!m_savedBlend.enabled)
gl.disableiOES(GraphicsContextGL::BLEND, 0);
} else {
gl.blendEquationSeparate(m_savedBlend.equationRGB, m_savedBlend.equationAlpha);
gl.blendFuncSeparate(m_savedBlend.srcRGB, m_savedBlend.dstRGB, m_savedBlend.srcAlpha, m_savedBlend.dstAlpha);
if (!m_savedBlend.enabled)
gl.disable(GraphicsContextGL::BLEND);
}
m_didApply = false;
}
static bool isHighPerformanceContext(const RefPtr<GraphicsContextGL>& context)
{
return context->contextAttributes().powerPreference == WebGLPowerPreference::HighPerformance;
}
// Counter for determining which context has the earliest active ordinal number.
static std::atomic<uint64_t> s_lastActiveOrdinal;
using WebGLRenderingContextBaseSet = HashSet<WebGLRenderingContextBase*>;
static WebGLRenderingContextBaseSet& activeContexts()
{
if (isMainThread()) {
// WebKitLegacy special case: check for main thread because TLS does not work when entering sometimes from
// WebThread and sometimes from real main thread.
// Leave this on for non-legacy cases, as this is the base case for current operation where offscreen canvas
// is not supported or is rarely used.
static NeverDestroyed<WebGLRenderingContextBaseSet> s_mainThreadActiveContexts;
return s_mainThreadActiveContexts.get();
}
static LazyNeverDestroyed<ThreadSpecific<WebGLRenderingContextBaseSet>> s_activeContexts;
static std::once_flag s_onceFlag;
std::call_once(s_onceFlag, [] {
s_activeContexts.construct();
});
return *s_activeContexts.get();
}
static void addActiveContext(WebGLRenderingContextBase& newContext)
{
auto& contexts = activeContexts();
auto maxContextsSize = isMainThread() ? maxActiveContexts : maxActiveWorkerContexts;
if (contexts.size() >= maxContextsSize) {
auto* earliest = *std::min_element(contexts.begin(), contexts.end(), [] (auto& a, auto& b) {
return a->activeOrdinal() < b->activeOrdinal();
});
earliest->recycleContext();
ASSERT(earliest != &newContext); // This assert is here so we can assert isNewEntry below instead of top-level `!contexts.contains(newContext);`.
ASSERT(contexts.size() < maxContextsSize);
}
auto result = contexts.add(&newContext);
ASSERT_UNUSED(result, result.isNewEntry);
}
static void removeActiveContext(WebGLRenderingContextBase& context)
{
bool didContain = activeContexts().remove(&context);
ASSERT_UNUSED(didContain, didContain);
}
static GraphicsClient* getGraphicsClient(CanvasBase& canvas)
{
if (auto* canvasElement = dynamicDowncast<HTMLCanvasElement>(canvas)) {
Document& document = canvasElement->document();
RefPtr<Frame> frame = document.frame();
if (!frame)
return nullptr;
return document.view()->root()->hostWindow();
}
if (is<WorkerGlobalScope>(canvas.scriptExecutionContext()))
return downcast<WorkerGlobalScope>(canvas.scriptExecutionContext())->workerClient();
return nullptr;
}
std::unique_ptr<WebGLRenderingContextBase> WebGLRenderingContextBase::create(CanvasBase& canvas, WebGLContextAttributes& attributes, WebGLVersion type)
{
auto scriptExecutionContext = canvas.scriptExecutionContext();
if (!scriptExecutionContext)
return nullptr;
#if ENABLE(WEBGL2)
// Note: WebGL 2.0 is only supported with the ANGLE backend.
if (type == GraphicsContextGLWebGLVersion::WebGL2 && !scriptExecutionContext->settingsValues().webGL2Enabled)
return nullptr;
#else
UNUSED_PARAM(type);
#endif
GraphicsClient* graphicsClient = getGraphicsClient(canvas);
auto* canvasElement = dynamicDowncast<HTMLCanvasElement>(canvas);
if (!scriptExecutionContext->settingsValues().webGLEnabled) {
canvasElement->dispatchEvent(WebGLContextEvent::create(eventNames().webglcontextcreationerrorEvent,
Event::CanBubble::No, Event::IsCancelable::Yes, "Web page was not allowed to create a WebGL context."_s));
return nullptr;
}
if (scriptExecutionContext->settingsValues().forceWebGLUsesLowPower) {
if (attributes.powerPreference == GraphicsContextGLPowerPreference::HighPerformance)
LOG(WebGL, "Overriding powerPreference from high-performance to low-power.");
attributes.powerPreference = GraphicsContextGLPowerPreference::LowPower;
}
if (canvasElement) {
Document& document = canvasElement->document();
RefPtr<Frame> frame = document.frame();
if (!frame)
return nullptr;
Document& topDocument = document.topDocument();
Page* page = topDocument.page();
if (page)
attributes.devicePixelRatio = page->deviceScaleFactor();
}
// FIXME: Should we try get the devicePixelRatio for workers for the page that created
// the worker? What if it's a shared worker, and there's multiple answers?
attributes.noExtensions = true;
attributes.shareResources = false;
attributes.initialPowerPreference = attributes.powerPreference;
attributes.webGLVersion = type;
#if PLATFORM(MAC)
// FIXME: Add MACCATALYST support for gpuIDForDisplay.
if (graphicsClient)
attributes.windowGPUID = gpuIDForDisplay(graphicsClient->displayID());
#endif
#if PLATFORM(COCOA)
attributes.useMetal = scriptExecutionContext->settingsValues().webGLUsingMetal;
#endif
RefPtr<GraphicsContextGL> context;
if (graphicsClient)
context = graphicsClient->createGraphicsContextGL(attributes);
if (!context) {
if (canvasElement) {
canvasElement->dispatchEvent(WebGLContextEvent::create(eventNames().webglcontextcreationerrorEvent,
Event::CanBubble::No, Event::IsCancelable::Yes, "Could not create a WebGL context."_s));
}
return nullptr;
}
std::unique_ptr<WebGLRenderingContextBase> renderingContext;
#if ENABLE(WEBGL2)
if (type == WebGLVersion::WebGL2)
renderingContext = WebGL2RenderingContext::create(canvas, context.releaseNonNull(), attributes);
else
#endif
renderingContext = WebGLRenderingContext::create(canvas, context.releaseNonNull(), attributes);
renderingContext->suspendIfNeeded();
return renderingContext;
}
WebGLRenderingContextBase::WebGLRenderingContextBase(CanvasBase& canvas, WebGLContextAttributes attributes)
: GPUBasedCanvasRenderingContext(canvas)
, m_restoreTimer(canvas.scriptExecutionContext(), *this, &WebGLRenderingContextBase::maybeRestoreContext)
, m_attributes(attributes)
, m_numGLErrorsToConsoleAllowed(maxGLErrorsAllowedToConsole)
, m_checkForContextLossHandlingTimer(*this, &WebGLRenderingContextBase::checkForContextLossHandling)
#if ENABLE(WEBXR)
, m_isXRCompatible(attributes.xrCompatible)
#endif
{
m_restoreTimer.suspendIfNeeded();
registerWithWebGLStateTracker();
if (canvas.isHTMLCanvasElement())
m_checkForContextLossHandlingTimer.startOneShot(checkContextLossHandlingDelay);
}
WebGLRenderingContextBase::WebGLRenderingContextBase(CanvasBase& canvas, Ref<GraphicsContextGL>&& context, WebGLContextAttributes attributes)
: GPUBasedCanvasRenderingContext(canvas)
, m_restoreTimer(canvas.scriptExecutionContext(), *this, &WebGLRenderingContextBase::maybeRestoreContext)
, m_generatedImageCache(4)
, m_attributes(attributes)
, m_numGLErrorsToConsoleAllowed(maxGLErrorsAllowedToConsole)
, m_checkForContextLossHandlingTimer(*this, &WebGLRenderingContextBase::checkForContextLossHandling)
#if ENABLE(WEBXR)
, m_isXRCompatible(attributes.xrCompatible)
#endif
{
setGraphicsContextGL(WTFMove(context));
m_restoreTimer.suspendIfNeeded();
m_contextGroup = WebGLContextGroup::create();
m_contextGroup->addContext(*this);
m_context->getIntegerv(GraphicsContextGL::MAX_VIEWPORT_DIMS, m_maxViewportDims);
setupFlags();
registerWithWebGLStateTracker();
if (canvas.isHTMLCanvasElement())
m_checkForContextLossHandlingTimer.startOneShot(checkContextLossHandlingDelay);
addActivityStateChangeObserverIfNecessary();
}
WebGLCanvas WebGLRenderingContextBase::canvas()
{
auto& base = canvasBase();
#if ENABLE(OFFSCREEN_CANVAS)
if (is<OffscreenCanvas>(base))
return &downcast<OffscreenCanvas>(base);
#endif
return &downcast<HTMLCanvasElement>(base);
}
#if ENABLE(OFFSCREEN_CANVAS)
OffscreenCanvas* WebGLRenderingContextBase::offscreenCanvas()
{
auto& base = canvasBase();
if (!is<OffscreenCanvas>(base))
return nullptr;
return &downcast<OffscreenCanvas>(base);
}
#endif
// We check for context loss handling after a few seconds to give the JS a chance to register the event listeners
// and to discard temporary GL contexts (e.g. feature detection).
void WebGLRenderingContextBase::checkForContextLossHandling()
{
auto canvas = htmlCanvas();
if (!canvas)
return;
if (!canvas->renderer())
return;
auto* page = canvas->document().page();
if (!page)
return;
bool handlesContextLoss = canvas->hasEventListeners(eventNames().webglcontextlostEvent) && canvas->hasEventListeners(eventNames().webglcontextrestoredEvent);
page->diagnosticLoggingClient().logDiagnosticMessage(DiagnosticLoggingKeys::pageHandlesWebGLContextLossKey(), handlesContextLoss ? DiagnosticLoggingKeys::yesKey() : DiagnosticLoggingKeys::noKey(), ShouldSample::No);
}
void WebGLRenderingContextBase::registerWithWebGLStateTracker()
{
auto canvas = htmlCanvas();
if (!canvas)
return;
auto* page = canvas->document().page();
if (!page)
return;
auto* tracker = page->webGLStateTracker();
if (!tracker)
return;
m_trackerToken = tracker->token(m_attributes.initialPowerPreference);
}
void WebGLRenderingContextBase::initializeNewContext()
{
ASSERT(!isContextLost());
m_needsUpdate = true;
m_markedCanvasDirty = false;
m_activeTextureUnit = 0;
m_packAlignment = 4;
m_unpackAlignment = 4;
m_unpackFlipY = false;
m_unpackPremultiplyAlpha = false;
m_unpackColorspaceConversion = GraphicsContextGL::BROWSER_DEFAULT_WEBGL;
m_boundArrayBuffer = nullptr;
m_currentProgram = nullptr;
m_framebufferBinding = nullptr;
m_renderbufferBinding = nullptr;
m_depthMask = true;
m_stencilEnabled = false;
m_stencilMask = 0xFFFFFFFF;
m_stencilMaskBack = 0xFFFFFFFF;
m_stencilFuncRef = 0;
m_stencilFuncRefBack = 0;
m_stencilFuncMask = 0xFFFFFFFF;
m_stencilFuncMaskBack = 0xFFFFFFFF;
m_layerCleared = false;
m_numGLErrorsToConsoleAllowed = maxGLErrorsAllowedToConsole;
m_rasterizerDiscardEnabled = false;
m_clearColor[0] = m_clearColor[1] = m_clearColor[2] = m_clearColor[3] = 0;
m_scissorEnabled = false;
m_clearDepth = 1;
m_clearStencil = 0;
m_colorMask[0] = m_colorMask[1] = m_colorMask[2] = m_colorMask[3] = true;
GCGLint numCombinedTextureImageUnits = m_context->getInteger(GraphicsContextGL::MAX_COMBINED_TEXTURE_IMAGE_UNITS);
if (numCombinedTextureImageUnits < 8) {
// OpenGL ES 2.0 sets the minimum for
// GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS to 8. Receiving a value less than
// 8 means an error with the context. Signal that the context is lost.
forceContextLost();
return;
}
m_textureUnits.clear();
m_textureUnits.resize(numCombinedTextureImageUnits);
GCGLint numVertexAttribs = m_context->getInteger(GraphicsContextGL::MAX_VERTEX_ATTRIBS);
if (numVertexAttribs < 8) {
// OpenGL ES 2.0 sets the minimum for GL_MAX_VERTEX_ATTRIBS to
// 8. Receiving a value less than 8 means an error with the
// context. Signal that the context is lost.
forceContextLost();
return;
}
m_maxVertexAttribs = numVertexAttribs;
m_vertexAttribValue.clear();
m_vertexAttribValue.resize(m_maxVertexAttribs);
m_maxTextureSize = m_context->getInteger(GraphicsContextGL::MAX_TEXTURE_SIZE);
m_maxTextureLevel = WebGLTexture::computeLevelCount(m_maxTextureSize, m_maxTextureSize);
m_maxCubeMapTextureSize = m_context->getInteger(GraphicsContextGL::MAX_CUBE_MAP_TEXTURE_SIZE);
m_maxCubeMapTextureLevel = WebGLTexture::computeLevelCount(m_maxCubeMapTextureSize, m_maxCubeMapTextureSize);
m_maxRenderbufferSize = m_context->getInteger(GraphicsContextGL::MAX_RENDERBUFFER_SIZE);
// These two values from EXT_draw_buffers are lazily queried.
m_maxDrawBuffers = 0;
m_maxColorAttachments = 0;
m_backDrawBuffer = GraphicsContextGL::BACK;
m_drawBuffersWebGLRequirementsChecked = false;
m_drawBuffersSupported = false;
m_context->setDrawingBufferColorSpace(toDestinationColorSpace(m_drawingBufferColorSpace));
IntSize canvasSize = clampedCanvasSize();
m_context->reshape(canvasSize.width(), canvasSize.height());
m_context->viewport(0, 0, canvasSize.width(), canvasSize.height());
m_context->scissor(0, 0, canvasSize.width(), canvasSize.height());
m_supportedTexImageSourceInternalFormats.clear();
m_supportedTexImageSourceFormats.clear();
m_supportedTexImageSourceTypes.clear();
m_areWebGL2TexImageSourceFormatsAndTypesAdded = false;
m_areOESTextureFloatFormatsAndTypesAdded = false;
m_areOESTextureHalfFloatFormatsAndTypesAdded = false;
m_areEXTsRGBFormatsAndTypesAdded = false;
ADD_VALUES_TO_SET(m_supportedTexImageSourceInternalFormats, SupportedFormatsES2);
ADD_VALUES_TO_SET(m_supportedTexImageSourceFormats, SupportedFormatsES2);
ADD_VALUES_TO_SET(m_supportedTexImageSourceTypes, SupportedTypesES2);
initializeVertexArrayObjects();
}
void WebGLRenderingContextBase::setupFlags()
{
ASSERT(m_context);
auto canvas = htmlCanvas();
if (canvas) {
if (Page* page = canvas->document().page())
m_synthesizedErrorsToConsole = page->settings().webGLErrorsToConsoleEnabled();
}
// FIXME: With ANGLE as a backend this probably isn't needed any more. Unfortunately
// turning it off causes problems.
m_isGLES2Compliant = m_context->isGLES2Compliant();
if (m_isGLES2Compliant) {
m_isGLES2NPOTStrict = !m_context->isExtensionEnabled("GL_OES_texture_npot"_s);
m_isDepthStencilSupported = m_context->isExtensionEnabled("GL_OES_packed_depth_stencil"_s) || m_context->isExtensionEnabled("GL_ANGLE_depth_texture"_s);
} else {
m_isGLES2NPOTStrict = true;
m_isDepthStencilSupported = m_context->isExtensionEnabled("GL_EXT_packed_depth_stencil"_s) || m_context->isExtensionEnabled("GL_ANGLE_depth_texture"_s);
}
m_isRobustnessEXTSupported = m_context->isExtensionEnabled("GL_EXT_robustness"_s);
}
void WebGLRenderingContextBase::addCompressedTextureFormat(GCGLenum format)
{
if (!m_compressedTextureFormats.contains(format))
m_compressedTextureFormats.append(format);
}
void WebGLRenderingContextBase::resetUnpackParameters()
{
if (m_unpackAlignment != 1)
m_context->pixelStorei(GraphicsContextGL::UNPACK_ALIGNMENT, 1);
}
void WebGLRenderingContextBase::restoreUnpackParameters()
{
if (m_unpackAlignment != 1)
m_context->pixelStorei(GraphicsContextGL::UNPACK_ALIGNMENT, m_unpackAlignment);
}
void WebGLRenderingContextBase::addActivityStateChangeObserverIfNecessary()
{
// We are only interested in visibility changes for contexts
// that are using the high-performance GPU.
if (!isHighPerformanceContext(m_context))
return;
auto* canvas = htmlCanvas();
if (!canvas)
return;
auto* page = canvas->document().page();
if (!page)
return;
page->addActivityStateChangeObserver(*this);
// We won't get a state change right away, so
// make sure the context knows if it visible or not.
if (m_context)
m_context->setContextVisibility(page->isVisible());
}
void WebGLRenderingContextBase::removeActivityStateChangeObserver()
{
auto* canvas = htmlCanvas();
if (canvas) {
if (auto* page = canvas->document().page())
page->removeActivityStateChangeObserver(*this);
}
}
WebGLRenderingContextBase::~WebGLRenderingContextBase()
{
// Remove all references to WebGLObjects so if they are the last reference
// they will be freed before the last context is removed from the context group.
m_boundArrayBuffer = nullptr;
m_defaultVertexArrayObject = nullptr;
m_boundVertexArrayObject = nullptr;
m_currentProgram = nullptr;
m_framebufferBinding = nullptr;
m_renderbufferBinding = nullptr;
for (auto& textureUnit : m_textureUnits) {
textureUnit.texture2DBinding = nullptr;
textureUnit.textureCubeMapBinding = nullptr;
}
m_blackTexture2D = nullptr;
m_blackTextureCubeMap = nullptr;
detachAndRemoveAllObjects();
loseExtensions(LostContextMode::RealLostContext);
destroyGraphicsContextGL();
m_contextGroup->removeContext(*this);
{
Locker locker { WebGLProgram::instancesLock() };
for (auto& entry : WebGLProgram::instances()) {
if (entry.value == this) {
// Don't remove any WebGLProgram from the instances list, as they may still exist.
// Only remove the association with a WebGL context.
entry.value = nullptr;
}
}
}
}
void WebGLRenderingContextBase::setGraphicsContextGL(Ref<GraphicsContextGL>&& context)
{
bool wasActive = m_context;
if (m_context) {
m_context->setClient(nullptr);
m_context = nullptr;
}
m_context = WTFMove(context);
m_context->setClient(this);
updateActiveOrdinal();
if (!wasActive)
addActiveContext(*this);
}
void WebGLRenderingContextBase::destroyGraphicsContextGL()
{
removeActivityStateChangeObserver();
if (m_context) {
m_context->setClient(nullptr);
m_context = nullptr;
removeActiveContext(*this);
}
}
void WebGLRenderingContextBase::markContextChanged()
{
if (m_framebufferBinding)
return;
m_context->markContextChanged();
m_layerCleared = false;
m_compositingResultsNeedUpdating = true;
if (auto* canvas = htmlCanvas()) {
RenderBox* renderBox = canvas->renderBox();
if (isAccelerated() && renderBox && renderBox->hasAcceleratedCompositing()) {
m_markedCanvasDirty = true;
canvas->clearCopiedImage();
renderBox->contentChanged(CanvasPixelsChanged);
return;
}
}
if (!m_markedCanvasDirty) {
m_markedCanvasDirty = true;
canvasBase().didDraw(FloatRect(FloatPoint(0, 0), clampedCanvasSize()));
}
}
void WebGLRenderingContextBase::markContextChangedAndNotifyCanvasObserver(WebGLRenderingContextBase::CallerType caller)
{
// Draw and clear ops with rasterizer discard enabled do not change the canvas.
if (caller == CallerTypeDrawOrClear && m_rasterizerDiscardEnabled)
return;
// If we're not touching the default framebuffer, nothing visible has changed.
if (m_framebufferBinding)
return;
markContextChanged();
if (!isAccelerated())
return;
auto* canvas = htmlCanvas();
if (!canvas)
return;
canvas->notifyObserversCanvasChanged(FloatRect(FloatPoint(0, 0), clampedCanvasSize()));
}
bool WebGLRenderingContextBase::clearIfComposited(WebGLRenderingContextBase::CallerType caller, GCGLbitfield mask)
{
if (isContextLost())
return false;
// `clearIfComposited()` is a function that prepares for updates. Mark the context as active.
updateActiveOrdinal();
if (!m_context->layerComposited() || m_layerCleared || m_preventBufferClearForInspector)
return false;
GCGLbitfield buffersNeedingClearing = m_context->getBuffersToAutoClear();
if (!buffersNeedingClearing || (mask && m_framebufferBinding) || (m_rasterizerDiscardEnabled && caller == CallerTypeDrawOrClear))
return false;
// Use the underlying GraphicsContext3D's attributes to take into
// account (for example) packed depth/stencil buffers.
auto contextAttributes = m_context->contextAttributes();
// Determine if it's possible to combine the clear the user asked for and this clear.
bool combinedClear = mask && !m_scissorEnabled;
m_context->disable(GraphicsContextGL::SCISSOR_TEST);
if (combinedClear && (mask & GraphicsContextGL::COLOR_BUFFER_BIT) && (m_backDrawBuffer != GraphicsContextGL::NONE)) {
m_context->clearColor(m_colorMask[0] ? m_clearColor[0] : 0,
m_colorMask[1] ? m_clearColor[1] : 0,
m_colorMask[2] ? m_clearColor[2] : 0,
m_colorMask[3] ? m_clearColor[3] : 0);
} else
m_context->clearColor(0, 0, 0, 0);
if (m_oesDrawBuffersIndexed)
m_context->colorMaskiOES(0, true, true, true, true);
else
m_context->colorMask(true, true, true, true);
GCGLbitfield clearMask = GraphicsContextGL::COLOR_BUFFER_BIT;
if (contextAttributes.depth) {
if (!combinedClear || !m_depthMask || !(mask & GraphicsContextGL::DEPTH_BUFFER_BIT))
m_context->clearDepth(1.0f);
clearMask |= GraphicsContextGL::DEPTH_BUFFER_BIT;
m_context->depthMask(true);