-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathwebgl_context.hpp
More file actions
1136 lines (1057 loc) · 45.7 KB
/
webgl_context.hpp
File metadata and controls
1136 lines (1057 loc) · 45.7 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
#pragma once
#include <array>
#include <string>
#include <memory>
#include <optional>
#include <unordered_map>
#include <vector>
#include <chrono>
#include <glm/glm.hpp>
#include <common/utility.hpp>
#include <common/command_buffers/webgl_constants.hpp>
#include <client/scripting_base/v8_object_holder.hpp>
#include <client/xr/common.hpp>
#include "../per_process.hpp"
#include "./webgl_program.hpp"
#include "./webgl_shader.hpp"
#include "./webgl_shader_precision_format.hpp"
#include "./webgl_buffer.hpp"
#include "./webgl_framebuffer.hpp"
#include "./webgl_renderbuffer.hpp"
#include "./webgl_texture.hpp"
#include "./webgl_attrib_location.hpp"
#include "./webgl_uniform_location.hpp"
#include "./webgl_query.hpp"
#include "./webgl_sampler.hpp"
#include "./webgl_vertex_array.hpp"
#define WEBGL_DEBUG 1
// Uncomment to enable WebGL debugging mode.
// #undef WEBGL_DEBUG
namespace endor
{
namespace client_graphics
{
enum class WebGLError
{
kNoError = WEBGL_NO_ERROR,
kInvalidEnum = WEBGL_INVALID_ENUM,
kInvalidValue = WEBGL_INVALID_VALUE,
kInvalidOperation = WEBGL_INVALID_OPERATION,
kInvalidFramebufferOperation = WEBGL_INVALID_FRAMEBUFFER_OPERATION,
kOutOfMemory = WEBGL_OUT_OF_MEMORY,
kContextLost = WEBGL_CONTEXT_LOST_WEBGL
};
enum class WebGLDrawMode
{
kPoints = WEBGL_POINTS,
kLineStrip = WEBGL_LINE_STRIP,
kLineLoop = WEBGL_LINE_LOOP,
kLines = WEBGL_LINES,
kTriangleStrip = WEBGL_TRIANGLE_STRIP,
kTriangleFan = WEBGL_TRIANGLE_FAN,
kTriangles = WEBGL_TRIANGLES,
};
enum class WebGLHintTargetBehavior
{
kGenerateMipmap = WEBGL_GENERATE_MIPMAP_HINT,
kFragmentShaderDerivative = WEBGL2_FRAGMENT_SHADER_DERIVATIVE_HINT,
};
enum class WebGLHintBehaviorMode
{
kFastest = WEBGL_FASTEST,
kNicest = WEBGL_NICEST,
kDontCare = WEBGL_DONT_CARE,
};
enum class WebGLPixelStorageParameterName
{
kPackAlignment = WEBGL_PACK_ALIGNMENT,
kUnpackAlignment = WEBGL_UNPACK_ALIGNMENT,
kUnpackFlipY = WEBGL_UNPACK_FLIP_Y_WEBGL,
kUnpackPremultiplyAlpha = WEBGL_UNPACK_PREMULTIPLY_ALPHA_WEBGL,
kUnpackColorspaceConversion = WEBGL_UNPACK_COLORSPACE_CONVERSION_WEBGL,
// WebGL2
kUnpackRowLength = WEBGL2_UNPACK_ROW_LENGTH,
kUnpackSkipRows = WEBGL2_UNPACK_SKIP_ROWS,
kUnpackSkipPixels = WEBGL2_UNPACK_SKIP_PIXELS,
kUnpackSkipImages = WEBGL2_UNPACK_SKIP_IMAGES,
kPackRowLength = WEBGL2_PACK_ROW_LENGTH,
kPackSkipRows = WEBGL2_PACK_SKIP_ROWS,
kPackSkipPixels = WEBGL2_PACK_SKIP_PIXELS,
};
enum class WebGLBooleanParameterName
{
kBlend = WEBGL_BLEND,
kCullFace = WEBGL_CULL_FACE,
kDepthTest = WEBGL_DEPTH_TEST,
kDepthWrite = WEBGL_DEPTH_WRITEMASK,
kDither = WEBGL_DITHER,
kPolygonOffsetFill = WEBGL_POLYGON_OFFSET_FILL,
kSampleCoverageInvert = WEBGL_SAMPLE_COVERAGE_INVERT,
kScissorTest = WEBGL_SCISSOR_TEST,
kStencilTest = WEBGL_STENCIL_TEST,
kUnpackFlipY = WEBGL_UNPACK_FLIP_Y_WEBGL,
kUnpackPremultiplyAlpha = WEBGL_UNPACK_PREMULTIPLY_ALPHA_WEBGL,
};
enum class WebGLFloatParameterName
{
// TODO: Add more
};
enum class WebGLFloatArrayParameterName
{
kViewport = WEBGL_VIEWPORT,
kScissorBox = WEBGL_SCISSOR_BOX,
};
enum class WebGLIntegerParameterName
{
kActiveTexture = WEBGL_ACTIVE_TEXTURE,
kAlphaBits = WEBGL_ALPHA_BITS,
kBlendDstAlpha = WEBGL_BLEND_DST_ALPHA,
kBlendDstRgb = WEBGL_BLEND_DST_RGB,
kBlendEquation = WEBGL_BLEND_EQUATION,
kBlendEquationAlpha = WEBGL_BLEND_EQUATION_ALPHA,
kBlendEquationRgb = WEBGL_BLEND_EQUATION_RGB,
kBlendSrcAlpha = WEBGL_BLEND_SRC_ALPHA,
kBlendSrcRgb = WEBGL_BLEND_SRC_RGB,
kBlueBits = WEBGL_BLUE_BITS,
kCullFaceMode = WEBGL_CULL_FACE_MODE,
kDepthBits = WEBGL_DEPTH_BITS,
kDepthFunc = WEBGL_DEPTH_FUNC,
kFrontFace = WEBGL_FRONT_FACE,
kGenerateMipmapHint = WEBGL_GENERATE_MIPMAP_HINT,
kGreenBits = WEBGL_GREEN_BITS,
kImplementationColorReadFormat = WEBGL_IMPLEMENTATION_COLOR_READ_FORMAT,
kImplementationColorReadType = WEBGL_IMPLEMENTATION_COLOR_READ_TYPE,
kMaxCombinedTextureImageUnits = WEBGL_MAX_COMBINED_TEXTURE_IMAGE_UNITS,
kMaxCubeMapTextureSize = WEBGL_MAX_CUBE_MAP_TEXTURE_SIZE,
kMaxFragmentUniformVectors = WEBGL_MAX_FRAGMENT_UNIFORM_VECTORS,
kMaxRenderbufferSize = WEBGL_MAX_RENDERBUFFER_SIZE,
kMaxTextureImageUnits = WEBGL_MAX_TEXTURE_IMAGE_UNITS,
kMaxTextureSize = WEBGL_MAX_TEXTURE_SIZE,
kMaxVaryingVectors = WEBGL_MAX_VARYING_VECTORS,
kMaxVertexAttribs = WEBGL_MAX_VERTEX_ATTRIBS,
kMaxVertexTextureImageUnits = WEBGL_MAX_VERTEX_TEXTURE_IMAGE_UNITS,
kMaxVertexUniformVectors = WEBGL_MAX_VERTEX_UNIFORM_VECTORS,
kPackAlignment = WEBGL_PACK_ALIGNMENT,
kRedBits = WEBGL_RED_BITS,
kSampleBuffers = WEBGL_SAMPLE_BUFFERS,
kSamples = WEBGL_SAMPLES,
kStencilBackFail = WEBGL_STENCIL_BACK_FAIL,
kStencilBackFunc = WEBGL_STENCIL_BACK_FUNC,
kStencilBackPassDepthFail = WEBGL_STENCIL_BACK_PASS_DEPTH_FAIL,
kStencilBackPassDepthPass = WEBGL_STENCIL_BACK_PASS_DEPTH_PASS,
kStencilBackRef = WEBGL_STENCIL_BACK_REF,
kStencilBackValueMask = WEBGL_STENCIL_BACK_VALUE_MASK,
kStencilBackWriteMask = WEBGL_STENCIL_BACK_WRITEMASK,
kStencilBits = WEBGL_STENCIL_BITS,
kStencilFail = WEBGL_STENCIL_FAIL,
kStencilFunc = WEBGL_STENCIL_FUNC,
kStencilPassDepthFail = WEBGL_STENCIL_PASS_DEPTH_FAIL,
kStencilPassDepthPass = WEBGL_STENCIL_PASS_DEPTH_PASS,
kStencilRef = WEBGL_STENCIL_REF,
kStencilValueMask = WEBGL_STENCIL_VALUE_MASK,
kStencilWriteMask = WEBGL_STENCIL_WRITEMASK,
kSubpixelBits = WEBGL_SUBPIXEL_BITS,
kUnpackAlignment = WEBGL_UNPACK_ALIGNMENT,
kUnpackColorspaceConversion = WEBGL_UNPACK_COLORSPACE_CONVERSION_WEBGL
};
enum class WebGLInteger64ParameterName
{
// TODO: Add more
};
enum class WebGLBooleanIndexedParameterName
{
// TODO: Add more
};
enum class WebGLStringParameterName
{
kRenderer = WEBGL_RENDERER,
kShadingLanguageVersion = WEBGL_SHADING_LANGUAGE_VERSION,
kVendor = WEBGL_VENDOR,
kVersion = WEBGL_VERSION,
};
enum class WebGL2IntegerParameterName
{
kMax3DTextureSize = WEBGL2_MAX_3D_TEXTURE_SIZE,
kMaxArrayTextureLayers = WEBGL2_MAX_ARRAY_TEXTURE_LAYERS,
kMaxColorAttachments = WEBGL2_MAX_COLOR_ATTACHMENTS,
kMaxCombinedUniformBlocks = WEBGL2_MAX_COMBINED_UNIFORM_BLOCKS,
kMaxDrawBuffers = WEBGL2_MAX_DRAW_BUFFERS,
kMaxElementsIndices = WEBGL2_MAX_ELEMENTS_INDICES,
kMaxElementsVertices = WEBGL2_MAX_ELEMENTS_VERTICES,
kMaxFragmentInputComponents = WEBGL2_MAX_FRAGMENT_INPUT_COMPONENTS,
kMaxFragmentUniformBlocks = WEBGL2_MAX_FRAGMENT_UNIFORM_BLOCKS,
kMaxFragmentUniformComponents = WEBGL2_MAX_FRAGMENT_UNIFORM_COMPONENTS,
kMaxProgramTexelOffset = WEBGL2_MAX_PROGRAM_TEXEL_OFFSET,
kMaxSamples = WEBGL2_MAX_SAMPLES,
kMaxTransformFeedbackInterleavedComponents = WEBGL2_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS,
kMaxTransformFeedbackSeparateAttribs = WEBGL2_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS,
kMaxTransformFeedbackSeparateComponents = WEBGL2_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS,
kMaxUniformBufferBindings = WEBGL2_MAX_UNIFORM_BUFFER_BINDINGS,
kMaxVaryingComponents = WEBGL2_MAX_VARYING_COMPONENTS,
kMaxVertexOutputComponents = WEBGL2_MAX_VERTEX_OUTPUT_COMPONENTS,
kMaxVertexUniformBlocks = WEBGL2_MAX_VERTEX_UNIFORM_BLOCKS,
kMaxVertexUniformComponents = WEBGL2_MAX_VERTEX_UNIFORM_COMPONENTS,
kMinProgramTexelOffset = WEBGL2_MIN_PROGRAM_TEXEL_OFFSET,
kMaxClientWaitTimeoutWebGL = WEBGL2_MAX_CLIENT_WAIT_TIMEOUT_WEBGL,
kMaxCombinedFragmentUniformComponents = WEBGL2_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS,
kMaxCombinedVertexUniformComponents = WEBGL2_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS,
kMaxElementIndex = WEBGL2_MAX_ELEMENT_INDEX,
kMaxServerWaitTimeout = WEBGL2_MAX_SERVER_WAIT_TIMEOUT,
kMaxUniformBlockSize = WEBGL2_MAX_UNIFORM_BLOCK_SIZE,
kMaxTextureLodBias = WEBGL2_MAX_TEXTURE_LOD_BIAS,
kExtMaxViewsOvr = WEBGL2_EXT_MAX_VIEWS_OVR,
};
class ContextAttributes final
{
public:
bool alpha = true;
bool antialias = true;
bool depth = true;
bool stencil = false;
bool failIfMajorPerformanceCaveat = false;
bool premultipliedAlpha = false;
bool preserveDrawingBuffer = false;
bool xrCompatible = false;
std::string powerPreference = "default";
};
/**
* The `WebGLState` class represents the current state of the `WebGLRenderingContext` object.
*/
class WebGLState
{
public:
/**
* It restores the given `WebGLState` object to the current rendering state.
*
* @param state The `WebGLState` object to restore.
* @param context The `WebGL2Context` object to restore the state to.
*/
static void Restore(WebGLState &state, std::shared_ptr<WebGL2Context> context);
public:
WebGLState() = default;
// Check if the current drawing won't affect the color buffer.
inline bool hasNoColorMask() const
{
return !colorMask[0] && !colorMask[1] && !colorMask[2] && !colorMask[3];
}
public:
// bindings
std::optional<std::shared_ptr<WebGLProgram>> program = std::nullopt;
std::optional<std::shared_ptr<WebGLVertexArray>> vertexArray = std::nullopt;
std::optional<std::shared_ptr<WebGLBuffer>> vertexBuffer = std::nullopt;
std::optional<std::shared_ptr<WebGLBuffer>> elementBuffer = std::nullopt;
std::optional<std::shared_ptr<WebGLFramebuffer>> framebuffer = std::nullopt;
std::optional<std::shared_ptr<WebGLRenderbuffer>> renderbuffer = std::nullopt;
// states
std::array<bool, 4> colorMask = {true, true, true, true};
};
/**
* The `WebGLContext` class implements the WebGLRenderingContext interface in C/C++ at the client-side, this is used to
* implement the WebGL API, and support native C/C++ renderer.
*/
class WebGLContext : public scripting_base::JSObjectHolder
{
friend class WebGLProgramScope;
friend class client_xr::XRSession; // Allow XRSession to call `connectXRSession()`.
friend class client_xr::XRDeviceClient; // Allow XRDeviceClient to call `sendCommandBuffer()`.
public:
WebGLContext(ContextAttributes &attrs, bool isWebGL2 = false);
~WebGLContext();
public: // graphics methods
std::shared_ptr<WebGLProgram> createProgram();
void deleteProgram(std::shared_ptr<WebGLProgram> program);
void linkProgram(std::shared_ptr<WebGLProgram> program);
void validateProgram(std::shared_ptr<WebGLProgram> program);
void useProgram(std::shared_ptr<WebGLProgram> program);
void bindAttribLocation(std::shared_ptr<WebGLProgram> program, uint32_t index, const std::string &name);
int getProgramParameter(std::shared_ptr<WebGLProgram> program, int pname);
std::string getProgramInfoLog(std::shared_ptr<WebGLProgram> program);
std::shared_ptr<WebGLShader> createShader(WebGLShaderType type);
void deleteShader(std::shared_ptr<WebGLShader> shader);
void shaderSource(std::shared_ptr<WebGLShader> shader, const std::string &source);
void compileShader(std::shared_ptr<WebGLShader> shader);
void attachShader(std::shared_ptr<WebGLProgram> program, std::shared_ptr<WebGLShader> shader);
void detachShader(std::shared_ptr<WebGLProgram> program, std::shared_ptr<WebGLShader> shader);
std::string getShaderSource(std::shared_ptr<WebGLShader> shader);
int getShaderParameter(std::shared_ptr<WebGLShader> shader, int pname);
std::string getShaderInfoLog(std::shared_ptr<WebGLShader> shader);
std::shared_ptr<WebGLBuffer> createBuffer();
void deleteBuffer(std::shared_ptr<WebGLBuffer> buffer);
void bindBuffer(WebGLBufferBindingTarget target, std::shared_ptr<WebGLBuffer> buffer);
void bufferData(WebGLBufferBindingTarget target, size_t size, WebGLBufferUsage usage);
void bufferData(WebGLBufferBindingTarget target, size_t srcSize, void *srcData, WebGLBufferUsage usage);
void bufferSubData(WebGLBufferBindingTarget target, int offset, size_t size, void *data);
std::shared_ptr<WebGLFramebuffer> createFramebuffer();
void deleteFramebuffer(std::shared_ptr<WebGLFramebuffer> framebuffer);
void bindFramebuffer(WebGLFramebufferBindingTarget target, std::shared_ptr<WebGLFramebuffer> framebuffer);
void framebufferRenderbuffer(
WebGLFramebufferBindingTarget target,
WebGLFramebufferAttachment attachment,
WebGLRenderbufferBindingTarget renderbuffertarget,
std::shared_ptr<WebGLRenderbuffer> renderbuffer);
void framebufferTexture2D(
WebGLFramebufferBindingTarget target,
WebGLFramebufferAttachment attachment,
WebGLTexture2DTarget textarget,
std::shared_ptr<WebGLTexture> texture,
int level);
uint32_t checkFramebufferStatus(WebGLFramebufferBindingTarget target);
std::shared_ptr<WebGLRenderbuffer> createRenderbuffer();
void deleteRenderbuffer(std::shared_ptr<WebGLRenderbuffer> renderbuffer);
void bindRenderbuffer(WebGLRenderbufferBindingTarget target, std::shared_ptr<WebGLRenderbuffer> renderbuffer);
void renderbufferStorage(WebGLRenderbufferBindingTarget target, int internalformat, int width, int height);
std::shared_ptr<WebGLTexture> createTexture();
void deleteTexture(std::shared_ptr<WebGLTexture> texture);
void bindTexture(WebGLTextureTarget target, std::shared_ptr<WebGLTexture> texture);
void texImage2D(
WebGLTexture2DTarget target,
int level,
int internalformat,
size_t width,
size_t height,
int border,
WebGLTextureFormat format,
WebGLPixelType type,
unsigned char *pixels);
void texSubImage2D(
WebGLTexture2DTarget target,
int level,
int xoffset,
int yoffset,
size_t width,
size_t height,
WebGLTextureFormat format,
WebGLPixelType type,
unsigned char *pixels);
void copyTexImage2D(
WebGLTexture2DTarget target,
int level,
int internalformat,
int x,
int y,
size_t width,
size_t height,
int border);
void copyTexSubImage2D(
WebGLTexture2DTarget target,
int level,
int xoffset,
int yoffset,
int x,
int y,
size_t width,
size_t height);
void texParameterf(WebGLTextureTarget target, WebGLTextureParameterName pname, float param);
void texParameteri(WebGLTextureTarget target, WebGLTextureParameterName pname, int param);
void texParameterfv(WebGLTextureTarget target, WebGLTextureParameterName pname, const std::vector<float> params);
void texParameteriv(WebGLTextureTarget target, WebGLTextureParameterName pname, const std::vector<int> params);
void activeTexture(WebGLTextureUnit texture);
void generateMipmap(WebGLTextureTarget target);
void enableVertexAttribArray(const WebGLAttribLocation &);
void enableVertexAttribArray(int index);
void disableVertexAttribArray(const WebGLAttribLocation &);
void disableVertexAttribArray(int index);
void vertexAttribPointer(const WebGLAttribLocation &, size_t size, int type, bool normalized, size_t stride, int offset);
void vertexAttribPointer(int index, size_t size, int type, bool normalized, size_t stride, int offset);
void vertexAttrib1f(const WebGLAttribLocation &, float v0);
void vertexAttrib1f(int index, float v0);
void vertexAttrib2f(const WebGLAttribLocation &, float v0, float v1);
void vertexAttrib2f(int index, float v0, float v1);
void vertexAttrib3f(const WebGLAttribLocation &, float v0, float v1, float v2);
void vertexAttrib3f(int index, float v0, float v1, float v2);
void vertexAttrib4f(const WebGLAttribLocation &, float v0, float v1, float v2, float v3);
void vertexAttrib4f(int index, float v0, float v1, float v2, float v3);
void vertexAttrib1fv(const WebGLAttribLocation &, const std::vector<float> values);
void vertexAttrib1fv(int index, const std::vector<float> values);
void vertexAttrib2fv(const WebGLAttribLocation &, const std::vector<float> values);
void vertexAttrib2fv(int index, const std::vector<float> values);
void vertexAttrib3fv(const WebGLAttribLocation &, const std::vector<float> values);
void vertexAttrib3fv(int index, const std::vector<float> values);
void vertexAttrib4fv(const WebGLAttribLocation &, const std::vector<float> values);
void vertexAttrib4fv(int index, const std::vector<float> values);
std::optional<WebGLActiveInfo> getActiveAttrib(std::shared_ptr<WebGLProgram> program, unsigned int index);
std::optional<WebGLActiveInfo> getActiveUniform(std::shared_ptr<WebGLProgram> program, unsigned int index);
std::optional<WebGLAttribLocation> getAttribLocation(std::shared_ptr<WebGLProgram> program, const std::string &name);
std::optional<WebGLUniformLocation> getUniformLocation(std::shared_ptr<WebGLProgram> program, const std::string &name);
void uniform1f(WebGLUniformLocation location, float v0);
void uniform1fv(WebGLUniformLocation location, const std::vector<float> value);
void uniform1i(WebGLUniformLocation location, int v0);
void uniform1iv(WebGLUniformLocation location, const std::vector<int> value);
void uniform2f(WebGLUniformLocation location, float v0, float v1);
void uniform2fv(WebGLUniformLocation location, const std::vector<float> value);
void uniform2i(WebGLUniformLocation location, int v0, int v1);
void uniform2iv(WebGLUniformLocation location, const std::vector<int> value);
void uniform3f(WebGLUniformLocation location, float v0, float v1, float v2);
void uniform3fv(WebGLUniformLocation location, const std::vector<float> value);
void uniform3i(WebGLUniformLocation location, int v0, int v1, int v2);
void uniform3iv(WebGLUniformLocation location, const std::vector<int> value);
void uniform4f(WebGLUniformLocation location, float v0, float v1, float v2, float v3);
void uniform4fv(WebGLUniformLocation location, const std::vector<float> value);
void uniform4i(WebGLUniformLocation location, int v0, int v1, int v2, int v3);
void uniform4iv(WebGLUniformLocation location, const std::vector<int> value);
void uniformMatrix2fv(WebGLUniformLocation location, bool transpose, glm::mat2 m);
void uniformMatrix2fv(WebGLUniformLocation location, bool transpose, std::vector<float> values);
void uniformMatrix2fv(WebGLUniformLocation location, bool transpose, MatrixComputationGraph &graphToValues);
void uniformMatrix3fv(WebGLUniformLocation location, bool transpose, glm::mat3 m);
void uniformMatrix3fv(WebGLUniformLocation location, bool transpose, std::vector<float> values);
void uniformMatrix3fv(WebGLUniformLocation location, bool transpose, MatrixComputationGraph &graphToValues);
void uniformMatrix4fv(WebGLUniformLocation location, bool transpose, glm::mat4 m);
void uniformMatrix4fv(WebGLUniformLocation location, bool transpose, std::vector<float> values);
void uniformMatrix4fv(WebGLUniformLocation location, bool transpose, MatrixComputationGraph &graphToValues);
void drawArrays(WebGLDrawMode mode, int first, int count);
void drawElements(WebGLDrawMode mode, int count, int type, int offset);
void hint(WebGLHintTargetBehavior target, WebGLHintBehaviorMode mode);
void lineWidth(float width);
void pixelStorei(WebGLPixelStorageParameterName pname, int param);
void polygonOffset(float factor, float units);
void viewport(int x, int y, size_t width, size_t height);
void scissor(int x, int y, size_t width, size_t height);
void clearColor(float red, float green, float blue, float alpha);
void clearDepth(float depth);
void clearStencil(int s);
void clear(int mask = WEBGL_COLOR_BUFFER_BIT | WEBGL_DEPTH_BUFFER_BIT | WEBGL_STENCIL_BUFFER_BIT);
void depthMask(bool flag);
void depthFunc(int func);
void depthRange(float zNear, float zFar);
void stencilFunc(int func, int ref, unsigned int mask);
void stencilFuncSeparate(int face, int func, int ref, unsigned int mask);
void stencilMask(unsigned int mask);
void stencilMaskSeparate(int face, unsigned int mask);
void stencilOp(int fail, int zfail, int zpass);
void stencilOpSeparate(int face, int fail, int zfail, int zpass);
void blendColor(float red, float green, float blue, float alpha);
void blendEquation(int mode);
void blendEquationSeparate(int modeRGB, int modeAlpha);
void blendFunc(int sfactor, int dfactor);
void blendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha);
void colorMask(bool red, bool green, bool blue, bool alpha);
void cullFace(int mode);
void frontFace(int mode);
void enable(int cap);
void disable(int cap);
bool getParameter(WebGLBooleanParameterName pname);
float getParameter(WebGLFloatParameterName pname);
std::vector<float> getParameter(WebGLFloatArrayParameterName pname);
int getParameter(WebGLIntegerParameterName pname);
int64_t getParameter(WebGLInteger64ParameterName pname);
bool getParameter(WebGLBooleanIndexedParameterName pname, int index);
float getParameter(WebGLFloatArrayParameterName pname, int index);
std::string getParameter(WebGLStringParameterName pname);
WebGLShaderPrecisionFormat getShaderPrecisionFormat(int shadertype, int precisiontype);
int getError();
std::vector<std::string> &getSupportedExtensions();
bool supportsExtension(const std::string &extension);
bool makeXRCompatible();
public:
/**
* @returns the width of the current drawing buffer, commonly the bound framebuffer.
*/
inline int drawingBufferWidth()
{
return viewport_.width();
}
/**
* @returns the height of the current drawing buffer, commonly the bound framebuffer.
*/
inline int drawingBufferHeight()
{
return viewport_.height();
}
/**
* @returns if this context is a WebGL2 context.
*/
inline bool isWebGL2()
{
return isWebGL2_;
}
/**
* @returns if the context is lost.
*/
inline bool isContextLost()
{
return isContextLost_;
}
/**
* @returns if the context could be for WebXR rendering.
*/
inline bool isXRCompatible()
{
return contextAttributes.xrCompatible;
}
/**
* It sets the WebGL error for the function.
*
* @param func the function name that causes the error.
* @param error the WebGL error.
* @param message the error message for debugging.
*/
inline void setError(std::string func, WebGLError error, std::string message)
{
lastError_ = error;
#if WEBGL_DEBUG
std::cerr << func << "(): " << message << std::endl;
#endif
}
protected:
/**
* It sends a command buffer request directly to the client context, it only updates the command buffer's context id before
* sending.
*
* @param commandBuffer
* @param followsFlush - if true, the command buffer will be executed in the default queue.
* @returns if the command buffer request is sent successfully.
*/
inline bool sendCommandBufferRequestDirectly(commandbuffers::TrCommandBufferBase &commandBuffer, bool followsFlush = false)
{
commandBuffer.contextId = id;
bool r = clientContext_->sendCommandBufferRequest(commandBuffer, followsFlush);
return r;
}
/**
* It sends a command buffer request to the server.
*
* @param commandBuffer
* @param followsFlush - if true, the command buffer will be executed in the default queue.
* @returns if the command buffer request is sent successfully.
*/
bool sendCommandBufferRequest(commandbuffers::TrCommandBufferBase &commandBuffer, bool followsFlush = false);
/**
* Receives a command buffer response from the server, and returns the response as a pointer to the specified type.
*
* @param responseType The type of the response command buffer, that is used to check the response type.
* @param req The request command buffer that is used to match the response.
* @param timeout The timeout in milliseconds to wait for the response, default is 1000ms.
* @returns A pointer to the response command buffer of the specified type, or nullptr if the response is not
* received within the timeout or if the response type does not match.
*/
template <typename R>
R *recvResponse(commandbuffers::CommandBufferType responseType,
const commandbuffers::TrCommandBufferBase &req,
int timeout = 1000)
{
auto response = clientContext_->recvCommandBufferResponse(this, req.id, timeout);
if (response == nullptr) [[unlikely]]
return nullptr;
if (response->type != responseType) [[unlikely]]
{
std::cerr << "recvCommandBuffer(): "
<< "Unexpected response type(" << response->type << "), expected(" << responseType << ")"
<< std::endl;
assert(false && "Unexpected response type");
}
return dynamic_cast<R *>(response);
}
/**
* It receives a command buffer response **asynchronously**, and calls the callback function with the response.
*
* @param responseType The type of the response command buffer, that is used to check the response type.
* @param req The request command buffer that is used to match the response.
* @param callback The callback function that is called with the response command buffer of the specified type.
*/
template <typename R>
void recvResponseAsync(commandbuffers::CommandBufferType responseType,
const commandbuffers::TrCommandBufferBase &req,
std::function<void(const R &)> callback)
{
auto onResponse = [responseType, callback](const commandbuffers::TrCommandBufferBase &response)
{
if (response.type != responseType) [[unlikely]]
{
std::cerr << "recvCommandBufferAsync(): "
<< "Unexpected response type(" << response.type << "), expected(" << responseType << ")"
<< std::endl;
assert(false && "Unexpected response type");
}
callback(dynamic_cast<const R &>(response));
};
clientContext_->recvCommandBufferResponseAsync(this, req.id, onResponse);
}
bool sendFlushCommand(std::shared_ptr<client_xr::XRSession> session);
void sendFirstContentfulPaintMetrics();
/**
* It unpacks the pixels from the source buffer to the destination buffer.
*
* @param type The pixel type.
* @param format The pixel format.
* @param width The width of the image.
* @param height The height of the image.
* @param srcPixels The source pixels buffer.
* @param dstPixels The destination pixels buffer, if it is null, a new buffer will be created.
* @returns The destination pixels buffer.
*/
unsigned char *unpackPixels(
WebGLPixelType type,
WebGLTextureFormat format,
size_t width,
size_t height,
unsigned char *srcPixels,
unsigned char *dstPixels = nullptr)
{
if (srcPixels == nullptr) // return null if the input is null.
return nullptr;
// Compute the pixel size
int pixelSize = 1;
if (type == WebGLPixelType::kUnsignedByte || type == WebGLPixelType::kFloat)
{
if (type == WebGLPixelType::kFloat)
pixelSize = 4;
switch (format)
{
case WebGLTextureFormat::kAlpha:
case WebGLTextureFormat::kLuminance:
break;
case WebGLTextureFormat::kLuminanceAlpha:
pixelSize *= 2;
break;
case WebGLTextureFormat::kRGB:
pixelSize *= 3;
break;
case WebGLTextureFormat::kRGBA:
pixelSize *= 4;
break;
default:
break;
}
}
else
{
pixelSize = 2;
}
// Compute the row stride
int rowStride = width * pixelSize;
if ((rowStride % unpackAlignment_) != 0)
rowStride += unpackAlignment_ - (rowStride % unpackAlignment_);
int imageSize = rowStride * height;
unsigned char *unpacked = new unsigned char[imageSize];
if (unpackFlipY_)
{
for (int i = 0, j = height - 1; j >= 0; ++i, --j)
{
memcpy(
reinterpret_cast<void *>(unpacked + j * rowStride),
reinterpret_cast<void *>(srcPixels + i * rowStride),
width * pixelSize);
}
}
else
{
memcpy(
reinterpret_cast<void *>(unpacked),
reinterpret_cast<void *>(srcPixels),
imageSize);
}
if (
unpackPremultiplyAlpha_ &&
(format == WebGLTextureFormat::kLuminanceAlpha || format == WebGLTextureFormat::kRGBA))
{
for (int row = 0; row < height; ++row)
{
for (int col = 0; col < width; ++col)
{
unsigned char *pixel = unpacked + (row * rowStride) + (col * pixelSize);
if (format == WebGLTextureFormat::kLuminanceAlpha)
{
pixel[0] *= pixel[1] / 255.0f;
}
else if (type == WebGLPixelType::kUnsignedByte)
{
float scale = pixel[3] / 255.0f;
pixel[0] *= scale;
pixel[1] *= scale;
pixel[2] *= scale;
}
else if (type == WebGLPixelType::kUnsignedShort4444)
{
int r = pixel[0] & 0x0f;
int g = pixel[0] >> 4;
int b = pixel[1] & 0x0f;
int a = pixel[1] >> 4;
float scale = a / 15.0f;
r *= scale;
g *= scale;
b *= scale;
pixel[0] = r | (g << 4);
pixel[1] = b | (a << 4);
}
}
}
}
return unpacked;
}
private:
/**
* @returns the client state of the WebGL context.
*/
WebGLState &clientState()
{
return clientState_;
}
/**
* an XR-compatible WebGL context could be configured as an `XRWebGLLayer` object and be connected to a specific WebXR
* session. At the same time, each WebXR session could own 1 base layer, thus the XR-compatible WebGL context to a WebXR
* session is a one-to-one relationship.
*
* @returns the current connected WebXR session, or `nullptr` if it is not connected.
*/
inline std::shared_ptr<client_xr::XRSession> connectedXRSession()
{
return isXRCompatible() ? connectedXRSession_.lock() : nullptr;
}
/**
* It connects the current WebGL context to a WebXR session.
*
* @param session The WebXR session to connect.
*/
inline void connectXRSession(std::shared_ptr<client_xr::XRSession> session)
{
connectedXRSession_ = session;
}
public:
uint8_t id;
ContextAttributes contextAttributes;
int maxCombinedTextureImageUnits;
int maxCubeMapTextureSize;
int maxFragmentUniformVectors;
int maxRenderbufferSize;
int maxTextureImageUnits;
int maxTextureSize;
int maxVaryingVectors;
int maxVertexAttribs;
int maxVertexTextureImageUnits;
int maxVertexUniformVectors;
std::string vendor;
std::string version;
std::string renderer;
// The default handedness of the coordinate system to use.
commandbuffers::MatrixHandedness defaultCoordHandedness = commandbuffers::MatrixHandedness::MATRIX_RIGHT_HANDED;
protected:
TrClientContextPerProcess *clientContext_;
TrViewport viewport_;
WebGLState clientState_;
WebGLError lastError_ = WebGLError::kNoError;
std::optional<std::vector<std::string>> supportedExtensions_ = std::nullopt;
std::unordered_map<int, WebGLShaderPrecisionFormat> vertexShaderPrecisionFormats_;
std::unordered_map<int, WebGLShaderPrecisionFormat> fragmentShaderPrecisionFormats_;
bool isWebGL2_ = false;
bool isContextLost_ = false;
bool unpackFlipY_ = false;
bool unpackPremultiplyAlpha_ = false;
glm::vec4 clearColor_ = {0.0f, 0.0f, 0.0f, 1.0f};
float clearDepth_ = 1.0f;
int clearStencil_ = 0;
glm::vec4 blendColor_ = {0.0f, 0.0f, 0.0f, 1.0f};
/**
* TODO: Read the value from the host
*/
uint32_t unpackAlignment_ = 4;
private:
// XR-compatible field
weak_ptr<client_xr::XRSession> connectedXRSession_;
};
class WebGL2Context final : public WebGLContext
{
public:
static inline std::shared_ptr<WebGL2Context> Make(ContextAttributes &attrs)
{
return std::make_shared<WebGL2Context>(attrs);
}
public:
WebGL2Context(ContextAttributes &attrs);
public:
void beginQuery(WebGLQueryTarget target, std::shared_ptr<WebGLQuery> query);
void beginTransformFeedback(WebGLDrawMode mode);
void bindBufferBase(WebGLBufferBindingTarget target, uint32_t index, std::shared_ptr<WebGLBuffer> buffer);
void bindBufferRange(
WebGLBufferBindingTarget target,
uint32_t index,
std::shared_ptr<WebGLBuffer> buffer,
int offset,
size_t size);
void bindSampler(uint32_t unit, std::shared_ptr<WebGLSampler> sampler);
void bindVertexArray(std::shared_ptr<WebGLVertexArray> vertexArray);
void blitFramebuffer(
int srcX0,
int srcY0,
int srcX1,
int srcY1,
int dstX0,
int dstY0,
int dstX1,
int dstY1,
int mask,
int filter);
void bufferData(WebGLBufferBindingTarget target, size_t size, WebGLBufferUsage usage);
void bufferData(
WebGLBufferBindingTarget target,
size_t srcSize,
void *srcData,
WebGLBufferUsage usage,
std::optional<int> srcOffset = 0,
std::optional<int> length = 0);
void bufferSubData(
WebGLBufferBindingTarget target,
int dstByteOffset,
size_t srcSize,
void *srcData,
std::optional<int> srcOffset = std::nullopt,
std::optional<int> length = 0);
void clearBufferfv(WebGLFramebufferAttachmentType buffer, int drawbuffer, const std::vector<float> values);
void clearBufferiv(WebGLFramebufferAttachmentType buffer, int drawbuffer, const std::vector<int> values);
void clearBufferuiv(WebGLFramebufferAttachmentType buffer, int drawbuffer, const std::vector<unsigned int> values);
void clearBufferfi(WebGLFramebufferAttachmentType buffer, int drawbuffer, float depth, int stencil);
void compressedTexImage3D(
WebGLTexture3DTarget target,
int level,
int internalformat,
size_t width,
size_t height,
size_t depth,
int border,
size_t imageSize,
unsigned char *data);
void compressedTexSubImage3D(
WebGLTexture3DTarget target,
int level,
int xoffset,
int yoffset,
int zoffset,
size_t width,
size_t height,
size_t depth,
int format,
size_t imageSize,
unsigned char *data);
void copyBufferSubData(
WebGLBufferBindingTarget readTarget,
WebGLBufferBindingTarget writeTarget,
int readOffset,
int writeOffset,
size_t size);
void copyTexSubImage3D(
WebGLTexture2DTarget target,
int level,
int xoffset,
int yoffset,
int zoffset,
int x,
int y,
size_t width,
size_t height);
std::shared_ptr<WebGLQuery> createQuery();
std::shared_ptr<WebGLSampler> createSampler();
std::shared_ptr<WebGLVertexArray> createVertexArray();
void deleteQuery(std::shared_ptr<WebGLQuery> query);
void deleteSampler(std::shared_ptr<WebGLSampler> sampler);
void deleteVertexArray(std::shared_ptr<WebGLVertexArray> vertexArray);
void drawArraysInstanced(WebGLDrawMode mode, int first, int count, int instanceCount);
void drawBuffers(const std::vector<uint32_t> buffers);
void drawElementsInstanced(WebGLDrawMode mode, int count, int type, int offset, int instanceCount);
void drawRangeElements(WebGLDrawMode mode, int start, int end, int count, int type, int offset);
void endQuery(WebGLQueryTarget target);
void framebufferTextureLayer(
WebGLFramebufferBindingTarget target,
WebGLFramebufferAttachment attachment,
std::shared_ptr<WebGLTexture> texture,
int level,
int layer);
std::string getActiveUniformBlockName(std::shared_ptr<WebGLProgram> program, int uniformBlockIndex);
void getBufferSubData(
WebGLBufferBindingTarget target,
int srcByteOffset,
size_t dstSize,
void *dstData,
std::optional<int> dstOffset = std::nullopt,
std::optional<int> length = std::nullopt);
int getFragDataLocation(std::shared_ptr<WebGLProgram> program, const std::string &name);
int getParameterV2(WebGL2IntegerParameterName pname);
std::shared_ptr<WebGLQuery> getQuery(WebGLQueryTarget target, int pname);
int getUniformBlockIndex(std::shared_ptr<WebGLProgram> program, const std::string &uniformBlockName);
void invalidateFramebuffer(WebGLFramebufferBindingTarget target, const std::vector<int> attachments);
void invalidateSubFramebuffer(
WebGLFramebufferBindingTarget target,
const std::vector<int> attachments,
int x,
int y,
size_t width,
size_t height);
bool isQuery(std::shared_ptr<WebGLQuery> query);
bool isSampler(std::shared_ptr<WebGLSampler> sampler);
bool isVertexArray(std::shared_ptr<WebGLVertexArray> vertexArray);
void readBuffer(int src);
void renderbufferStorageMultisample(WebGLRenderbufferBindingTarget target,
int samples,
int internalformat,
int width,
int height);
void texImage3D(WebGLTexture3DTarget target,
int level,
int internalformat,
size_t width,
size_t height,
size_t depth,
int border,
WebGLTextureFormat format,
WebGLPixelType type,
unsigned char *pixels);
void texStorage2D(WebGLTexture2DTarget target,
int levels,
int internalformat,
size_t width,
size_t height);
void texStorage3D(WebGLTexture3DTarget target,
int levels,
int internalformat,
size_t width,
size_t height,
size_t depth);
void texSubImage3D(WebGLTexture3DTarget target,
int level,
int xoffset,
int yoffset,
int zoffset,
size_t width,
size_t height,
size_t depth,
WebGLTextureFormat format,
WebGLPixelType type,
unsigned char *pixels);
void uniformBlockBinding(std::shared_ptr<WebGLProgram> program, int uniformBlockIndex, uint32_t uniformBlockBinding);
void uniformMatrix3x2fv(WebGLUniformLocation location, bool transpose, std::vector<float> values);
void uniformMatrix4x2fv(WebGLUniformLocation location, bool transpose, std::vector<float> values);
void uniformMatrix2x3fv(WebGLUniformLocation location, bool transpose, std::vector<float> values);
void uniformMatrix4x3fv(WebGLUniformLocation location, bool transpose, std::vector<float> values);
void uniformMatrix2x4fv(WebGLUniformLocation location, bool transpose, std::vector<float> values);
void uniformMatrix3x4fv(WebGLUniformLocation location, bool transpose, std::vector<float> values);
void vertexAttribDivisor(const WebGLAttribLocation &, uint32_t divisor);
void vertexAttribDivisor(int index, uint32_t divisor);
void vertexAttribI4i(const WebGLAttribLocation &, int v0, int v1, int v2, int v3);
void vertexAttribI4i(int index, int v0, int v1, int v2, int v3);
void vertexAttribI4ui(const WebGLAttribLocation &, uint v0, uint v1, uint v2, uint v3);
void vertexAttribI4ui(int index, uint v0, uint v1, uint v2, uint v3);
void vertexAttribI4iv(const WebGLAttribLocation &, const std::vector<int> values);
void vertexAttribI4iv(int index, const std::vector<int> values);
void vertexAttribI4uiv(const WebGLAttribLocation &, const std::vector<uint> values);