summaryrefslogtreecommitdiffstats
path: root/src/plugins/platforms/webgl/qwebglcontext.cpp
blob: 38eaf0fc64cd092dbf9bc1350217e7ea108e1da1 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
/****************************************************************************
**
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt WebGL module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 or (at your option) any later version
** approved by the KDE Free Qt Foundation. The licenses are as published by
** the Free Software Foundation and appearing in the file LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qwebglcontext.h"

#include "qwebglfunctioncall.h"
#include "qwebglintegration.h"
#include "qwebglintegration_p.h"
#include "qwebglwebsocketserver.h"
#include "qwebglwindow.h"
#include "qwebglwindow_p.h"

#include <QtCore/qhash.h>
#include <QtCore/qrect.h>
#include <QtCore/qset.h>
#include <QtGui/private/qguiapplication_p.h>
#include <QtGui/qguiapplication.h>
#include <QtGui/qimage.h>
#include <QtGui/qopenglcontext.h>
#include <QtGui/qsurface.h>
#include <QtWebSockets/qwebsocket.h>

#include <cstring>

QT_BEGIN_NAMESPACE

static Q_LOGGING_CATEGORY(lc, "qt.qpa.webgl.context")

struct PixelStorageModes
{
    PixelStorageModes() : unpackAlignment(4) { }
    int unpackAlignment;
};

struct ContextData {
    GLuint currentProgram = 0;
    GLuint boundArrayBuffer = 0;
    GLuint boundElementArrayBuffer = 0;
    GLuint boundTexture2D = 0;
    GLenum activeTextureUnit = GL_TEXTURE0;
    GLuint boundDrawFramebuffer = 0;
//    GLuint boundReadFramebuffer = 0;
    GLuint unpackAlignment = 4;
    struct VertexAttrib {
        VertexAttrib() : arrayBufferBinding(0), pointer(0), enabled(false) { }
        GLuint arrayBufferBinding;
        void *pointer;
        bool enabled;
        GLint size;
        GLenum type;
        bool normalized;
        GLsizei stride;
    };
    QHash<GLuint, VertexAttrib> vertexAttribPointers;
    QHash<GLuint, QImage> images;
    PixelStorageModes pixelStorage;
    QMap<GLenum, QVariant> cachedParameters;
    QSet<QByteArray> stringCache;
};

static QHash<int, ContextData> s_contextData;

QWebGLContext *currentContext()
{
    auto context = QOpenGLContext::currentContext();
    if (context)
        return static_cast<QWebGLContext *>(context->handle());
    return nullptr;
}

ContextData *currentContextData()
{
    auto context = currentContext();
    if (context)
        return &s_contextData[context->id()];
    return nullptr;
}

inline int imageSize(GLsizei width, GLsizei height, GLenum format, GLenum type,
                     const PixelStorageModes &pixelStorage)
{
    Q_UNUSED(pixelStorage); // TODO: Support different pixelStorage formats

    static struct BppTabEntry {
        GLenum format;
        GLenum type;
        int bytesPerPixel;
    } bppTab[] = {
        { GL_RGBA, GL_UNSIGNED_BYTE, 4 },
        { GL_RGBA, GL_BYTE, 4 },
        { GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, 2 },
        { GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, 2 },
        { GL_RGBA, GL_FLOAT, 16 },
        { GL_RGB, GL_UNSIGNED_BYTE, 3 },
        { GL_RGB, GL_BYTE, 3 },
        { GL_RGB, GL_UNSIGNED_SHORT_5_6_5, 2 },
        { GL_RGB, GL_FLOAT, 12 },

        { GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, 2 },
        { GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, 4 },
        { GL_DEPTH_COMPONENT, GL_FLOAT, 4 },

        { GL_RGBA, GL_UNSIGNED_BYTE, 4 },
        { GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, 2 },
        { GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, 2 },
        { GL_RGB, GL_UNSIGNED_BYTE, 3 },
        { GL_RGB, GL_UNSIGNED_SHORT_5_6_5, 2 },
        { GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, 1 },
        { GL_LUMINANCE, GL_UNSIGNED_BYTE, 1 },
        { GL_ALPHA, GL_UNSIGNED_BYTE, 1 },

        { GL_BGRA_EXT, GL_UNSIGNED_BYTE, 4 },
        { GL_BGRA_EXT, GL_BYTE, 4 },
        { GL_BGRA_EXT, GL_UNSIGNED_SHORT_4_4_4_4, 2 },
        { GL_BGRA_EXT, GL_UNSIGNED_SHORT_5_5_5_1, 2 },
        { GL_BGRA_EXT, GL_FLOAT, 16 }
    };

    int bytesPerPixel = 0;
    for (size_t i = 0; i < sizeof(bppTab) / sizeof(BppTabEntry); ++i) {
        if (bppTab[i].format == format && bppTab[i].type == type) {
            bytesPerPixel = bppTab[i].bytesPerPixel;
            break;
        }
    }

    const int rowSize = width * bytesPerPixel;
    if (!bytesPerPixel)
        qCWarning(lc, "Unknown texture format %x - %x", format, type);

    return rowSize * height;
}

QByteArrayList strings;

static void lockMutex()
{
    QWebGLIntegrationPrivate::instance()->webSocketServer->mutex()->lock();
}

static void waitCondition(unsigned long time = ULONG_MAX)
{
    auto mutex = QWebGLIntegrationPrivate::instance()->webSocketServer->mutex();
    auto waitCondition = QWebGLIntegrationPrivate::instance()->webSocketServer->waitCondition();
    waitCondition->wait(mutex, time);
}

static void unlockMutex()
{
    auto mutex = QWebGLIntegrationPrivate::instance()->webSocketServer->mutex();
    mutex->unlock();
}

static QVariant queryValue(int id)
{
    return QWebGLContext::queryValue(id);
}

static int elementSize(GLenum type)
{
    switch (type) {
    case GL_SHORT:
    case GL_UNSIGNED_SHORT:
        return 2;
    case GL_FLOAT:
    case GL_FIXED:
    case GL_INT:
    case GL_UNSIGNED_INT:
        return 4;
    default:
        return 1;
    }
}

static int vertexSize(GLint elementsPerVertex, GLenum type)
{
    return elementSize(type) * elementsPerVertex;
}

static int bufferSize(GLsizei count, GLint elemsPerVertex, GLenum type, GLsizei stride)
{
    if (count == 0)
        return 0;

    int vsize = vertexSize(elemsPerVertex, type);

    if (stride == 0)
        stride = vsize;

    return vsize + (count - 1) * stride;
}

static void setVertexAttribs(QWebGLFunctionCall *event, GLsizei count)
{
    event->addInt(currentContextData()->vertexAttribPointers.count());
    QHashIterator<GLuint, ContextData::VertexAttrib> it(currentContextData()->vertexAttribPointers);
    while (it.hasNext()) {
        it.next();
        const ContextData::VertexAttrib &va(it.value());
        if (va.arrayBufferBinding == 0 && va.enabled) {
            int len = bufferSize(count, va.size, va.type, va.stride);
            event->addUInt(it.key());
            event->addInt(va.size);
            event->addInt(va.type);
            event->addInt(va.normalized);
            event->addInt(va.stride);
            // found an enabled vertex attribute that was specified with a client-side pointer
            event->addData(QByteArray((const char *)va.pointer, len));
        }
    }
}

namespace QWebGL {

static void glActiveTexture(GLenum texture)
{
    auto event = currentContext()->createEvent(QStringLiteral("activeTexture"));
    if (!event)
        return;
    event->addInt(texture);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    currentContextData()->activeTextureUnit = texture;
}

static void glAttachShader(GLuint program, GLuint shader)
{
    auto event = currentContext()->createEvent(QStringLiteral("attachShader"));
    if (!event)
        return;
    event->addUInt(program);
    event->addUInt(shader);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glBindAttribLocation(GLuint program, GLuint index, const GLchar * name)
{
    auto event = currentContext()->createEvent(QStringLiteral("bindAttribLocation"));
    if (!event)
        return;
    event->addUInt(program);
    event->addUInt(index);
    event->addString(name);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glBindBuffer(GLenum target, GLuint buffer)
{
    if (target == GL_ARRAY_BUFFER)
        currentContextData()->boundArrayBuffer = buffer;
    if (target == GL_ELEMENT_ARRAY_BUFFER)
        currentContextData()->boundElementArrayBuffer = buffer;

    auto event = currentContext()->createEvent(QStringLiteral("bindBuffer"));
    if (!event)
        return;
    event->addInt(target);
    event->addUInt(buffer);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glBindFramebuffer(GLenum target, GLuint framebuffer)
{
    auto event = currentContext()->createEvent(QStringLiteral("bindFramebuffer"));
    if (!event)
        return;
    event->addInt(target);
    event->addUInt(framebuffer);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);

    if (target == GL_FRAMEBUFFER)
        currentContextData()->boundDrawFramebuffer = framebuffer;
}

static void glBindRenderbuffer(GLenum target, GLuint renderbuffer)
{
    auto event = currentContext()->createEvent(QStringLiteral("bindRenderbuffer"));
    if (!event)
        return;
    event->addInt(target);
    event->addUInt(renderbuffer);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glBindTexture(GLenum target, GLuint texture)
{
    auto event = currentContext()->createEvent(QStringLiteral("bindTexture"));
    if (!event)
        return;
    event->addInt(target);
    event->addUInt(texture);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    if (target == GL_TEXTURE_2D)
        currentContextData()->boundTexture2D = texture;
}

static void glBlendColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha)
{
    auto event = currentContext()->createEvent(QStringLiteral("blendColor"));
    if (!event)
        return;
    event->addFloat(red);
    event->addFloat(green);
    event->addFloat(blue);
    event->addFloat(alpha);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glBlendEquation(GLenum mode)
{
    auto event = currentContext()->createEvent(QStringLiteral("blendEquation"));
    if (!event)
        return;
    event->addInt(mode);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glBlendEquationSeparate(GLenum modeRGB, GLenum modeAlpha)
{
    auto event = currentContext()->createEvent(QStringLiteral("blendEquationSeparate"));
    if (!event)
        return;
    event->addInt(modeRGB);
    event->addInt(modeAlpha);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glBlendFunc(GLenum sfactor, GLenum dfactor)
{
    auto event = currentContext()->createEvent(QStringLiteral("blendFunc"));
    if (!event)
        return;
    event->addInt(sfactor);
    event->addInt(dfactor);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glBlendFuncSeparate(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha,
                                GLenum dfactorAlpha)
{
    auto event = currentContext()->createEvent(QStringLiteral("blendFuncSeparate"));
    if (!event)
        return;
    event->addInt(sfactorRGB);
    event->addInt(dfactorRGB);
    event->addInt(sfactorAlpha);
    event->addInt(dfactorAlpha);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glBufferData(GLenum target, GLsizeiptr size, const void * data, GLenum usage)
{
    auto event = currentContext()->createEvent(QStringLiteral("bufferData"));
    if (!event)
        return;
    event->addInt(target);
    event->addInt(usage);
    event->addInt(size);
    if (data)
        event->addData(QByteArray((const char *)data, size));
    else
        event->addData(QByteArray());
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glBufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, const void * data)
{
    auto event = currentContext()->createEvent(QStringLiteral("bufferSubData"));
    if (!event)
        return;
    event->addInt(target);
    event->addInt(size);
    event->addInt(offset);
    event->addData(QByteArray((const char *)data, size));
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static GLenum glCheckFramebufferStatus(GLenum target)
{
    auto event = currentContext()->createEvent(QStringLiteral("checkFramebufferStatus"), true);
    if (!event) return -1;
    const auto id =  event->id();
    event->addInt(target);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    auto value = queryValue(id).toInt();
    return value;
}

static void glClear(GLbitfield mask)
{
    auto event = currentContext()->createEvent(QStringLiteral("clear"));
    if (!event)
        return;
    event->addInt(mask);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glClearColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha)
{
    auto event = currentContext()->createEvent(QStringLiteral("clearColor"));
    if (!event)
        return;
    event->addFloat(red);
    event->addFloat(green);
    event->addFloat(blue);
    event->addFloat(alpha);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glClearDepthf(GLfloat d)
{
    auto event = currentContext()->createEvent(QStringLiteral("clearDepthf"));
    if (!event)
        return;
    event->addFloat(d);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glClearStencil(GLint s)
{
    auto event = currentContext()->createEvent(QStringLiteral("clearStencil"));
    if (!event)
        return;
    event->addInt(s);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glColorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha)
{
    auto event = currentContext()->createEvent(QStringLiteral("colorMask"));
    if (!event)
        return;
    event->addInt(red);
    event->addInt(green);
    event->addInt(blue);
    event->addInt(alpha);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glCompileShader(GLuint shader)
{
    auto event = currentContext()->createEvent(QStringLiteral("compileShader"));
    if (!event)
        return;
    event->addUInt(shader);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glCompressedTexImage2D(GLenum target, GLint level, GLenum internalformat,
                                   GLsizei width, GLsizei height, GLint border,
                                   GLsizei imageSize, const void * data)
{
    auto event = currentContext()->createEvent(QStringLiteral("compressedTexImage2D"));
    if (!event)
        return;
    event->addInt(target);
    event->addInt(level);
    event->addInt(internalformat);
    event->addInt(width);
    event->addInt(height);
    event->addInt(border);
    event->addInt(imageSize);
    event->addData(QByteArray((const char *) data, imageSize));
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glCompressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset,
                                      GLsizei width, GLsizei height, GLenum format,
                                      GLsizei imageSize, const void * data)
{
    auto event = currentContext()->createEvent(QStringLiteral("compressedTexSubImage2D"));
    if (!event)
        return;
    event->addInt(target);
    event->addInt(level);
    event->addInt(xoffset);
    event->addInt(yoffset);
    event->addInt(width);
    event->addInt(height);
    event->addInt(format);
    event->addInt(imageSize);
    event->addData(QByteArray((const char *) data, imageSize));
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glCopyTexImage2D(GLenum target, GLint level, GLenum internalformat, GLint x,
                             GLint y, GLsizei width, GLsizei height, GLint border)
{
    auto event = currentContext()->createEvent(QStringLiteral("copyTexImage2D"));
    if (!event)
        return;
    event->addInt(target);
    event->addInt(level);
    event->addInt(internalformat);
    event->addInt(x);
    event->addInt(y);
    event->addInt(width);
    event->addInt(height);
    event->addInt(border);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glCopyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset,
                                GLint x, GLint y, GLsizei width, GLsizei height)
{
    auto event = currentContext()->createEvent(QStringLiteral("copyTexSubImage2D"));
    if (!event)
        return;
    event->addInt(target);
    event->addInt(level);
    event->addInt(xoffset);
    event->addInt(yoffset);
    event->addInt(x);
    event->addInt(y);
    event->addInt(width);
    event->addInt(height);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static GLuint glCreateProgram()
{
    auto event = currentContext()->createEvent(QStringLiteral("createProgram"), true);
    if (!event) return -1;
    const auto id =  event->id();
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    const auto value = queryValue(id).toUInt();
    return value;
}

static GLuint glCreateShader(GLenum type)
{
    auto event = currentContext()->createEvent(QStringLiteral("createShader"), true);
    if (!event) return -1;
    const auto id =  event->id();
    event->addInt(type);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    const auto value = queryValue(id).toUInt();
    return value;
}

static void glCullFace(GLenum mode)
{
    auto event = currentContext()->createEvent(QStringLiteral("cullFace"));
    if (!event)
        return;
    event->addInt(mode);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glDeleteBuffers(GLsizei n, const GLuint * buffers)
{
    auto event = currentContext()->createEvent(QStringLiteral("deleteBuffers"));
    if (!event)
        return;
    event->addInt(n);
    for (int i = 0; i < n; ++i) {
        event->addUInt(buffers[i]);
        if (currentContextData()->boundArrayBuffer == buffers[i])
            currentContextData()->boundArrayBuffer = 0;
        if (currentContextData()->boundElementArrayBuffer == buffers[i])
            currentContextData()->boundElementArrayBuffer = 0;
    }
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glDeleteFramebuffers(GLsizei n, const GLuint * framebuffers)
{
    auto event = currentContext()->createEvent(QStringLiteral("deleteFramebuffers"));
    if (!event)
        return;
    event->addInt(n);
    for (int i = 0; i < n; ++i)
        event->addUInt(framebuffers[i]);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glDeleteProgram(GLuint program)
{
    auto event = currentContext()->createEvent(QStringLiteral("deleteProgram"));
    if (!event)
        return;
    event->addUInt(program);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glDeleteRenderbuffers(GLsizei n, const GLuint * renderbuffers)
{
    auto event = currentContext()->createEvent(QStringLiteral("deleteRenderbuffers"));
    if (!event)
        return;
    event->addInt(n);
    for (int i = 0; i < n; ++i)
        event->addUInt(renderbuffers[i]);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glDeleteShader(GLuint shader)
{
    auto event = currentContext()->createEvent(QStringLiteral("deleteShader"));
    if (!event)
        return;
    event->addUInt(shader);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glDeleteTextures(GLsizei n, const GLuint * textures)
{
    auto event = currentContext()->createEvent(QStringLiteral("deleteTextures"));
    if (!event)
        return;
    event->addInt(n);
    for (int i = 0; i < n; ++i)
        event->addUInt(textures[i]);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glDepthFunc(GLenum func)
{
    auto event = currentContext()->createEvent(QStringLiteral("depthFunc"));
    if (!event)
        return;
    event->addInt(func);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glDepthMask(GLboolean flag)
{
    auto event = currentContext()->createEvent(QStringLiteral("depthMask"));
    if (!event)
        return;
    event->addInt(flag);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glDepthRangef(GLfloat n, GLfloat f)
{
    auto event = currentContext()->createEvent(QStringLiteral("depthRangef"));
    if (!event)
        return;
    event->addFloat(n);
    event->addFloat(f);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glDetachShader(GLuint program, GLuint shader)
{
    auto event = currentContext()->createEvent(QStringLiteral("detachShader"));
    if (!event)
        return;
    event->addUInt(program);
    event->addUInt(shader);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glDisableVertexAttribArray(GLuint index)
{
    auto event = currentContext()->createEvent(QStringLiteral("disableVertexAttribArray"));
    if (!event)
        return;
    currentContextData()->vertexAttribPointers[index].enabled = false;
    event->addUInt(index);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glDrawArrays(GLenum mode, GLint first, GLsizei count)
{
    auto event = currentContext()->createEvent(QStringLiteral("drawArrays"));
    if (!event)
        return;
    event->addInt(mode);
    event->addInt(first);
    event->addInt(count);
    // Some vertex attributes may be client-side, others may not. Therefore
    // client-side ones need to transfer the data starting from the base
    // pointer, not just from 'first'.
    setVertexAttribs(event, first + count);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glDrawElements(GLenum mode, GLsizei count, GLenum type, const void * indices)
{
    auto event = currentContext()->createEvent(QStringLiteral("drawElements"), false);
    if (!event)
        return;
    event->addInt(mode);
    event->addInt(count);
    event->addInt(type);
    setVertexAttribs(event, count);
    ContextData *d = currentContextData();
    if (d->boundElementArrayBuffer == 0) {
        event->addInt(0);
        QByteArray data((const char *) indices, count * elementSize(type));
        event->addData(data.data());
    } else {
        event->addInt(1);
        event->addUInt((quintptr) indices);
    }

    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glEnableVertexAttribArray(GLuint index)
{
    auto event = currentContext()->createEvent(QStringLiteral("enableVertexAttribArray"));
    if (!event)
        return;
    currentContextData()->vertexAttribPointers[index].enabled = true;
    event->addUInt(index);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glFinish()
{
    auto event = currentContext()->createEvent(QStringLiteral("finish"));
    if (!event)
        return;
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glFlush()
{
    auto event = currentContext()->createEvent(QStringLiteral("flush"));
    if (!event)
        return;
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glFramebufferRenderbuffer(GLenum target, GLenum attachment,
                                      GLenum renderbuffertarget, GLuint renderbuffer)
{
    auto event = currentContext()->createEvent(QStringLiteral("framebufferRenderbuffer"));
    if (!event)
        return;
    event->addInt(target);
    event->addInt(attachment);
    event->addInt(renderbuffertarget);
    event->addUInt(renderbuffer);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget,
                                       GLuint texture, GLint level)
{
    auto event = currentContext()->createEvent(QStringLiteral("framebufferTexture2D"));
    if (!event)
        return;
    event->addInt(target);
    event->addInt(attachment);
    event->addInt(textarget);
    event->addUInt(texture);
    event->addInt(level);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glFrontFace(GLenum mode)
{
    auto event = currentContext()->createEvent(QStringLiteral("frontFace"));
    if (!event)
        return;
    event->addInt(mode);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glGenBuffers(GLsizei n, GLuint* buffers)
{
    auto event = currentContext()->createEvent(QStringLiteral("genBuffers"), true);
    if (!event)
        return;
    const auto id =  event->id();
    event->addInt(n);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    const auto values = queryValue(id).toList();
    if (values.size() != n) {
        qCWarning(lc, "Failed to create buffers");
        return;
    }
    for (int i = 0; i < n; ++i)
        buffers[i] = values.at(i).toUInt();
}

static void glGenFramebuffers(GLsizei n, GLuint* framebuffers)
{
    auto event = currentContext()->createEvent(QStringLiteral("genFramebuffers"), true);
    if (!event)
        return;
    const auto id = event->id();
    event->addInt(n);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    const auto values = queryValue(id).toList();
    if (values.size() != n) {
        qCWarning(lc, "Failed to create framebuffers");
        return;
    }
    for (int i = 0; i < n; ++i)
        framebuffers[i] = values.at(i).toUInt();
}

static void glGenRenderbuffers(GLsizei n, GLuint* renderbuffers)
{
    auto event = currentContext()->createEvent(QStringLiteral("genRenderbuffers"), true);
    if (!event)
        return;
    const auto id = event->id();
    event->addInt(n);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    const auto values = queryValue(id).toList();
    if (values.size() != n) {
        qCWarning(lc, "Failed to create render buffers");
        return;
    }
    for (int i = 0; i < n; ++i)
        renderbuffers[i] = values.at(i).toUInt();
}

static void glGenTextures(GLsizei n, GLuint* textures)
{
    auto event = currentContext()->createEvent(QStringLiteral("genTextures"), true);
    if (!event)
        return;
    const auto id = event->id();
    event->addInt(n);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    const auto variant = queryValue(id);
    const auto values = variant.toList();
    if (values.size() != n) {
        qCWarning(lc, "Failed to create textures");
        return;
    }
    for (int i = 0; i < n; ++i)
        textures[i] = values.at(i).toUInt();
}

static void glGenerateMipmap(GLenum target)
{
    auto event = currentContext()->createEvent(QStringLiteral("generateMipmap"));
    if (!event)
        return;
    event->addInt(target);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glGetActiveAttrib(GLuint program, GLuint index, GLsizei bufSize, GLsizei* length,
                              GLint* size, GLenum* type, GLchar* name)
{
    auto event = currentContext()->createEvent(QStringLiteral("getActiveAttrib"), true);
    if (!event)
        return;
    const auto id = event->id();
    event->addUInt(program);
    event->addUInt(index);
    event->addInt(bufSize);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    const auto values = queryValue(id).toMap();
    int rtype = values["rtype"].toInt();
    int rsize = values["rsize"].toInt();
    QByteArray rname = values["rname"].toByteArray();
    if (type)
        *type = rtype;
    if (size)
        *size = rsize;
    int len = qMax(0, qMin(bufSize - 1, rname.size()));
    if (length)
        *length = len;
    if (name) {
        memcpy(name, rname.constData(), len);
        name[len] = '\0';
    }
}

static void glGetActiveUniform(GLuint program, GLuint index, GLsizei bufSize, GLsizei* length,
                               GLint* size, GLenum* type, GLchar* name)
{
    auto event = currentContext()->createEvent(QStringLiteral("getActiveUniform"), true);
    if (!event)
        return;
    const auto id = event->id();
    event->addUInt(program);
    event->addUInt(index);
    event->addInt(bufSize);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    const auto values = queryValue(id).toMap();
    int rtype = values["rtype"].toInt();
    const auto rsize = values["rsize"].toInt();
    const auto rname = values["rname"].toByteArray();
    if (type)
        *type = rtype;
    if (size)
        *size = rsize;
    int len = qMax(0, qMin(bufSize - 1, rname.size()));
    if (length)
        *length = len;
    if (name) {
        memcpy(name, rname.constData(), len);
        name[len] = '\0';
    }
}

static void glGetAttachedShaders(GLuint program, GLsizei maxCount, GLsizei* count,
                                 GLuint* shaders)
{
    auto event = currentContext()->createEvent(QStringLiteral("getAttachedShaders"),
                                                       true);
    if (!event)
        return;
    const auto id = event->id();
    event->addUInt(program);
    event->addInt(maxCount);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    const auto values = queryValue(id).toList();
    *count = values.size();
    for (int i = 0; i < values.size(); ++i)
        shaders[i] = values.at(i).toUInt();
}

static GLint glGetAttribLocation(GLuint program, const GLchar * name)
{
    auto event = currentContext()->createEvent(QStringLiteral("getAttribLocation"), true);
    if (!event) return -1;
    const auto id =  event->id();
    event->addUInt(program);
    event->addString(name);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    const auto value = queryValue(id).toInt();
    return value;
}

static const GLubyte *glGetString(GLenum name)
{
    const auto it = currentContextData()->cachedParameters.find(name);
    if (it != currentContextData()->cachedParameters.end()) {
        auto &stringCache = currentContextData()->stringCache;
        Q_ASSERT(it->type() == QVariant::String);
        const auto string = it->toString().toLatin1();

        {
            auto it = stringCache.find(string), end = stringCache.end();
            if (it == end)
                it = stringCache.insert(string);
            return (const GLubyte *)(it->constData());
        }
    }

    auto event = currentContext()->createEvent(QStringLiteral("getString"), true);
    if (!event) return nullptr;
    const auto id =  event->id();
    event->addInt(name);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    auto value = queryValue(id).toByteArray();
    qCDebug(lc, "glGetString: %x: %s", name, qPrintable(value));
    strings.append(value);
    return (const GLubyte *)strings.last().constData();
}

static void glGetIntegerv(GLenum pname, GLint* data)
{
    if (pname == GL_MAX_TEXTURE_SIZE) {
        *data = 512;
        return;
    }

    const auto it = currentContextData()->cachedParameters.find(pname);
    if (it != currentContextData()->cachedParameters.end()) {
        QList<QVariant> values;
        switch (it->type()) {
        case QVariant::Map: values = it->toMap().values(); break;
        case QVariant::List: values = it->toList(); break;
        default: values = QVariantList{ *it };
        }
        for (const auto integer : qAsConst(values)) {
            bool ok;
            *data = integer.toInt(&ok);
            if (!ok)
                qCWarning(lc, "Failed to cast value");
            ++data;
        }
        return;
    }

    switch (pname) {
    case GL_CURRENT_PROGRAM:
        *data = currentContextData()->currentProgram;
        return;
    case GL_FRAMEBUFFER_BINDING:
        *data = currentContextData()->boundDrawFramebuffer;
        return;
    case GL_ARRAY_BUFFER_BINDING:
        *data = currentContextData()->boundArrayBuffer;
        return;
    case GL_ELEMENT_ARRAY_BUFFER_BINDING:
        *data = currentContextData()->boundElementArrayBuffer;
        return;
    case GL_ACTIVE_TEXTURE:
        *data = currentContextData()->activeTextureUnit;
        return;
    case GL_TEXTURE_BINDING_2D:
        *data = currentContextData()->boundTexture2D;
        return;
    default:;
    }

    auto event = currentContext()->createEvent(QStringLiteral("getIntegerv"), true);
    if (!event)
        return;
    const auto id =  event->id();
    event->addInt(pname);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    const auto value = queryValue(id).toInt();
    qCDebug(lc, "glGetIntegerv: %x: %d", pname, value);
    *data = value;
}

static void glGetBooleanv(GLenum pname, GLboolean* data)
{
    const auto it = currentContextData()->cachedParameters.find(pname);
    if (it != currentContextData()->cachedParameters.end()) {
        Q_ASSERT(it->type() == QVariant::Bool);
        *data = it->toBool();
        return;
    }

    auto event = currentContext()->createEvent(QStringLiteral("getBooleanv"), true);
    if (!event)
        return;
    const auto id = event->id();
    event->addInt(pname);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    const auto value = queryValue(id).toInt();
    qCDebug(lc, "glGetBooleanv: %x, %d", pname, value);
    *data = value;
}

static void glEnable(GLenum cap)
{
    auto event = currentContext()->createEvent(QStringLiteral("enable"));
    if (!event)
        return;
    event->addInt(cap);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);

    auto it = currentContextData()->cachedParameters.find(cap);
    if (it != currentContextData()->cachedParameters.end()) {
        Q_ASSERT(it->type() == QVariant::Bool);
        it->setValue(true);
    }
}

static void glDisable(GLenum cap)
{
    auto event = currentContext()->createEvent(QStringLiteral("disable"));
    if (!event)
        return;
    event->addInt(cap);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);

    auto it = currentContextData()->cachedParameters.find(cap);
    if (it != currentContextData()->cachedParameters.end()) {
        Q_ASSERT(it->type() == QVariant::Bool);
        it->setValue(false);
    }
}

static void glGetBufferParameteriv(GLenum target, GLenum pname, GLint* params)
{
    auto event = currentContext()->createEvent(QStringLiteral("getBufferParameteriv"), true);
    if (!event)
        return;
    const auto id = event->id();
    event->addInt(target);
    event->addInt(pname);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    const auto value = queryValue(id).toInt();
    *params = value;
}

static GLenum glGetError()
{
    auto event = currentContext()->createEvent(QStringLiteral("getError"), true);
    if (!event) return GL_NO_ERROR;
    const auto id =  event->id();
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    const auto value = queryValue(id).toInt();
    return value;
}

static void glGetFloatv(GLenum pname, GLfloat* data)
{
    auto event = currentContext()->createEvent(QStringLiteral("getParameter"), true);
    if (!event)
        return;
    const auto id = event->id();
    event->addInt(pname);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    bool ok;
    const auto value = queryValue(id).toFloat(&ok);
    qCDebug(lc, "glGetFloatv: %x, %f", pname, value);
    if (!ok)
        qCCritical(lc, "Invalid value");
    else
        *data = value;
}

static void glGetFramebufferAttachmentParameteriv(GLenum target, GLenum attachment,
                                                  GLenum pname, GLint* params)
{
    auto event = currentContext()->createEvent(
                QStringLiteral("getFramebufferAttachmentParameteriv"), true);
    if (!event)
        return;
    const auto id = event->id();
    event->addInt(target);
    event->addInt(attachment);
    event->addInt(pname);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    bool ok;
    const auto value = queryValue(id).toInt(&ok);
    if (!ok)
        qCCritical(lc, "Invalid value");
    else
        *params = value;
}

static void glGetProgramInfoLog(GLuint program, GLsizei bufSize, GLsizei* length, GLchar* infoLog)
{
    auto event = currentContext()->createEvent(QStringLiteral("getProgramInfoLog"), true);
    if (!event)
        return;
    const auto id = event->id();
    event->addUInt(program);
    event->addInt(bufSize);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    const auto value = queryValue(id).toString();
    *length = value.length();
    if (bufSize >= value.length())
        std::memcpy(infoLog, value.constData(), value.length());
}

static void glGetProgramiv(GLuint program, GLenum pname, GLint* params)
{
    auto event = currentContext()->createEvent(QStringLiteral("getProgramiv"), true);
    if (!event)
        return;
    const auto id =  event->id();
    event->addUInt(program);
    event->addInt(pname);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    *params = queryValue(id).toInt();
}

static void glGetRenderbufferParameteriv(GLenum target, GLenum pname, GLint* params)
{
    auto event = currentContext()->createEvent(QStringLiteral("getRenderbufferParameteriv"),
                                               true);
    if (!event)
        return;
    const auto id = event->id();
    event->addInt(target);
    event->addInt(pname);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    *params = queryValue(id).toInt();
}

static void glGetShaderInfoLog(GLuint shader, GLsizei bufSize, GLsizei* length, GLchar* infoLog)
{
    auto event = currentContext()->createEvent(QStringLiteral("getShaderInfoLog"), true);
    if (!event)
        return;
    const auto id = event->id();
    event->addUInt(shader);
    event->addInt(bufSize);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    const auto value = queryValue(id).toString();
    *length = value.length();
    if (bufSize >= value.length())
        std::memcpy(infoLog, value.constData(), value.length());
}

static void glGetShaderPrecisionFormat(GLenum shadertype, GLenum precisiontype, GLint* range,
                                       GLint* precision)
{
    auto event = currentContext()->createEvent(QStringLiteral("getShaderPrecisionFormat"), true);
    if (!event)
        return;
    const auto id = event->id();
    event->addInt(shadertype);
    event->addInt(precisiontype);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    bool ok;
    const auto value = queryValue(id).toMap();
    range[0] = value.value(QStringLiteral("rangeMin")).toInt(&ok);
    if (!ok)
        qCCritical(lc, "Invalid rangeMin value");
    range[1] = value.value(QStringLiteral("rangeMax")).toInt(&ok);
    if (!ok)
        qCCritical(lc, "Invalid rangeMax value");
    *precision = value.value(QStringLiteral("precision")).toInt(&ok);
    if (!ok)
        qCCritical(lc, "Invalid precision value");
}

static void glGetShaderSource(GLuint shader, GLsizei bufSize, GLsizei* length, GLchar* source)
{
    auto event = currentContext()->createEvent(QStringLiteral("getShaderSource"), true);
    if (!event)
        return;
    const auto id = event->id();
    event->addUInt(shader);
    event->addInt(bufSize);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    const auto value = queryValue(id).toString().toLatin1();
    *length = value.length();
    if (bufSize >= value.length())
        std::memcpy(source, value.constData(), value.length());
}

static void glGetShaderiv(GLuint shader, GLenum pname, GLint* params)
{
    if (pname == GL_INFO_LOG_LENGTH) {
        GLsizei bufSize = 0;
        glGetShaderInfoLog(shader, bufSize, &bufSize, nullptr);
        *params = bufSize;
        return;
    }
    if (pname == GL_SHADER_SOURCE_LENGTH) {
        GLsizei bufSize = 0;
        glGetShaderSource(shader, bufSize, &bufSize, nullptr);
        *params = bufSize;
        return;
    }
    auto event = currentContext()->createEvent(QStringLiteral("getShaderiv"), true);
    if (!event)
        return;
    const auto id =  event->id();
    event->addUInt(shader);
    event->addInt(pname);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    *params = queryValue(id).toInt();
}

static void glGetTexParameterfv(GLenum target, GLenum pname, GLfloat* params)
{
    auto event = currentContext()->createEvent(QStringLiteral("getTexParameterfv"), true);
    if (!event)
        return;
    const auto id = event->id();
    event->addInt(target);
    event->addInt(pname);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    bool ok;
    *params = queryValue(id).toFloat(&ok);
    if (!ok)
        qCWarning(lc, "Failed to cast value");
}

static void glGetTexParameteriv(GLenum target, GLenum pname, GLint* params)
{
    auto event = currentContext()->createEvent(QStringLiteral("getTexParameteriv"), true);
    if (!event)
        return;
    const auto id = event->id();
    event->addInt(target);
    event->addInt(pname);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    bool ok;
    *params = queryValue(id).toInt(&ok);
    if (!ok)
        qCWarning(lc, "Failed to cast value");
}

static GLint glGetUniformLocation(GLuint program, const GLchar * name)
{
    auto event = currentContext()->createEvent(QStringLiteral("getUniformLocation"), true);
    if (!event) return -1;
    const auto id =  event->id();
    event->addUInt(program);
    event->addString(name);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    bool ok;
    const auto value = queryValue(id).toInt(&ok);
    if (!ok) {
        qCWarning(lc, "Failed to cast value");
        return -1;
    }
    return value;
}

static void glGetUniformfv(GLuint program, GLint location, GLfloat* params)
{
    auto event = currentContext()->createEvent(QStringLiteral("getUniformfv"), true);
    if (!event)
        return;
    const auto id = event->id();
    event->addUInt(program);
    event->addInt(location);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    bool ok;
    const auto value = queryValue(id).toFloat(&ok);
    if (!ok)
        qCWarning(lc, "Failed to cast value");
    *params = value;
}

static void glGetUniformiv(GLuint program, GLint location, GLint* params)
{
    auto event = currentContext()->createEvent(QStringLiteral("getUniformiv"), true);
    if (!event)
        return;
    const auto id = event->id();
    event->addUInt(program);
    event->addInt(location);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    bool ok;
    const auto value = queryValue(id).toInt(&ok);
    if (!ok)
        qCWarning(lc, "Failed to cast value");
    *params = value;
}

static void glGetVertexAttribPointerv(GLuint index, GLenum pname, void ** pointer)
{
    Q_UNUSED(pointer);
    qCCritical(lc, "Not supported");
    return;
    auto event = currentContext()->createEvent(QStringLiteral("getVertexAttribPointerv"));
    if (!event)
        return;
    event->addUInt(index);
    event->addInt(pname);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glGetVertexAttribfv(GLuint index, GLenum pname, GLfloat* params)
{
    auto event = currentContext()->createEvent(QStringLiteral("getVertexAttribfv"), true);
    if (!event)
        return;
    const auto id = event->id();
    event->addUInt(index);
    event->addInt(pname);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    bool ok;
    const auto value = queryValue(id).toFloat(&ok);
    if (!ok)
        qCWarning(lc, "Failed to cast value");
    *params = value;
}

static void glGetVertexAttribiv(GLuint index, GLenum pname, GLint* params)
{
    auto event = currentContext()->createEvent(QStringLiteral("getVertexAttribiv"), true);
    if (!event)
        return;
    const auto id = event->id();
    event->addUInt(index);
    event->addInt(pname);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    bool ok;
    const auto value = queryValue(id).toInt(&ok);
    if (!ok)
        qCWarning(lc, "Failed to cast value");
    *params = value;
}

static void glHint(GLenum target, GLenum mode)
{
    auto event = currentContext()->createEvent(QStringLiteral("hint"));
    if (!event)
        return;
    event->addInt(target);
    event->addInt(mode);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static GLboolean glIsBuffer(GLuint buffer)
{
    auto event = currentContext()->createEvent(QStringLiteral("isBuffer"), true);
    if (!event) return GL_FALSE;
    const auto id =  event->id();
    event->addUInt(buffer);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    auto value = queryValue(id).toInt();
    return value;
}

static GLboolean glIsEnabled(GLenum cap)
{
    auto event = currentContext()->createEvent(QStringLiteral("isEnabled"), true);
    if (!event) return GL_FALSE;
    const auto id =  event->id();
    event->addInt(cap);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    auto value = queryValue(id).toInt();
    return value;
}

static GLboolean glIsFramebuffer(GLuint framebuffer)
{
    auto event = currentContext()->createEvent(QStringLiteral("isFramebuffer"), true);
    if (!event) return GL_FALSE;
    const auto id =  event->id();
    event->addUInt(framebuffer);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    const auto value = queryValue(id).toInt();
    return value;
}

static GLboolean glIsProgram(GLuint program)
{
    auto event = currentContext()->createEvent(QStringLiteral("isProgram"), true);
    if (!event) return GL_FALSE;
    const auto id =  event->id();
    event->addUInt(program);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    const auto value = queryValue(id).toInt();
    return value;
}

static GLboolean glIsRenderbuffer(GLuint renderbuffer)
{
    auto event = currentContext()->createEvent(QStringLiteral("isRenderbuffer"), true);
    if (!event) return GL_FALSE;
    const auto id =  event->id();
    event->addUInt(renderbuffer);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    const auto value = queryValue(id).toInt();
    return value;
}

static GLboolean glIsShader(GLuint shader)
{
    auto event = currentContext()->createEvent(QStringLiteral("isShader"), true);
    if (!event) return GL_FALSE;
    const auto id =  event->id();
    event->addUInt(shader);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    const auto value = QWebGLIntegrationPrivate::instance()->webSocketServer->queryValue(id);
    return value.toInt();
}

static GLboolean glIsTexture(GLuint texture)
{
    auto event = currentContext()->createEvent(QStringLiteral("isTexture"), true);
    if (!event) return GL_FALSE;
    const auto id =  event->id();
    event->addUInt(texture);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    const auto value = queryValue(id).toInt();
    return value;
}

static void glLineWidth(GLfloat width)
{
    auto event = currentContext()->createEvent(QStringLiteral("lineWidth"));
    if (!event)
        return;
    event->addFloat(width);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glLinkProgram(GLuint program)
{
    auto event = currentContext()->createEvent(QStringLiteral("linkProgram"));
    if (!event)
        return;
    event->addUInt(program);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glPixelStorei(GLenum pname, GLint param)
{
    switch (pname) {
    case GL_UNPACK_ALIGNMENT: currentContextData()->unpackAlignment = param; break;
    }

    auto event = currentContext()->createEvent(QStringLiteral("pixelStorei"));
    if (!event)
        return;
    event->addInt(pname);
    event->addInt(param);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glPolygonOffset(GLfloat factor, GLfloat units)
{
    auto event = currentContext()->createEvent(QStringLiteral("polygonOffset"));
    if (!event)
        return;
    event->addFloat(factor);
    event->addFloat(units);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glReadPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format,
                         GLenum type, void * pixels)
{
    auto event = currentContext()->createEvent(QStringLiteral("readPixels"), true);
    if (!event)
        return;
    const auto id = event->id();
    event->addInt(x);
    event->addInt(y);
    event->addInt(width);
    event->addInt(height);
    event->addInt(format);
    event->addInt(type);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    const auto value = queryValue(id).toByteArray();
    std::memcpy(pixels, value.constData(), value.size());
}

static void glReleaseShaderCompiler()
{
    auto event = currentContext()->createEvent(QStringLiteral("releaseShaderCompiler"));
    if (!event)
        return;
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glRenderbufferStorage(GLenum target, GLenum internalformat, GLsizei width,
                                  GLsizei height)
{
    auto event = currentContext()->createEvent(QStringLiteral("renderbufferStorage"));
    if (!event)
        return;
    event->addInt(target);
    event->addInt(internalformat);
    event->addInt(width);
    event->addInt(height);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glSampleCoverage(GLfloat value, GLboolean invert)
{
    auto event = currentContext()->createEvent(QStringLiteral("sampleCoverage"));
    if (!event)
        return;
    event->addFloat(value);
    event->addInt(invert);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glScissor(GLint x, GLint y, GLsizei width, GLsizei height)
{
    auto event = currentContext()->createEvent(QStringLiteral("scissor"));
    if (!event)
        return;
    event->addInt(x);
    event->addInt(y);
    event->addInt(width);
    event->addInt(height);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glShaderBinary(GLsizei count, const GLuint * shaders, GLenum binaryformat,
                           const void * binary, GLsizei length)
{
    Q_UNUSED(count);
    Q_UNUSED(shaders);
    Q_UNUSED(binaryformat);
    Q_UNUSED(binary);
    Q_UNUSED(length);
    qFatal("WebGL does not allow precompiled shaders");
}

static void glShaderSource(GLuint shader, GLsizei count, const GLchar *const* string,
                           const GLint * length)
{
    auto event = currentContext()->createEvent(QStringLiteral("shaderSource"));
    if (!event)
        return;
    event->addUInt(shader);
    event->addInt(count);
    for (int i = 0; i < count; ++i) {
        if (!length)
            event->addString(QString::fromLatin1(string[i]));
        else
            event->addString(QString::fromLatin1(string[i], length[i]));
    }
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glStencilFunc(GLenum func, GLint ref, GLuint mask)
{
    auto event = currentContext()->createEvent(QStringLiteral("stencilFunc"));
    if (!event)
        return;
    event->addInt(func);
    event->addInt(ref);
    event->addUInt(mask);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glStencilFuncSeparate(GLenum face, GLenum func, GLint ref, GLuint mask)
{
    auto event = currentContext()->createEvent(QStringLiteral("stencilFuncSeparate"));
    if (!event)
        return;
    event->addInt(face);
    event->addInt(func);
    event->addInt(ref);
    event->addUInt(mask);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glStencilMask(GLuint mask)
{
    auto event = currentContext()->createEvent(QStringLiteral("stencilMask"));
    if (!event)
        return;
    event->addUInt(mask);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glStencilMaskSeparate(GLenum face, GLuint mask)
{
    auto event = currentContext()->createEvent(QStringLiteral("stencilMaskSeparate"));
    if (!event)
        return;
    event->addInt(face);
    event->addUInt(mask);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glStencilOp(GLenum fail, GLenum zfail, GLenum zpass)
{
    auto event = currentContext()->createEvent(QStringLiteral("stencilOp"));
    if (!event)
        return;
    event->addInt(fail);
    event->addInt(zfail);
    event->addInt(zpass);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glStencilOpSeparate(GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass)
{
    auto event = currentContext()->createEvent(QStringLiteral("stencilOpSeparate"));
    if (!event)
        return;
    event->addInt(face);
    event->addInt(sfail);
    event->addInt(dpfail);
    event->addInt(dppass);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glTexImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width,
                         GLsizei height, GLint border, GLenum format, GLenum type,
                         const void * pixels)
{
    auto event = currentContext()->createEvent(QStringLiteral("texImage2D"));
    if (!event)
        return;
    event->addInt(target);
    event->addInt(level);
    event->addInt(internalformat);
    event->addInt(width);
    event->addInt(height);
    event->addInt(border);
    event->addInt(format);
    event->addInt(type);

    if (pixels) {
        const int len = imageSize(width, height, format, type, currentContextData()->pixelStorage);
        event->addData(QByteArray((const char *)pixels, len));
    } else {
        event->addNull();
    }
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glTexParameterf(GLenum target, GLenum pname, GLfloat param)
{
    auto event = currentContext()->createEvent(QStringLiteral("texParameterf"));
    if (!event)
        return;
    event->addInt(target);
    event->addInt(pname);
    event->addFloat(param);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glTexParameterfv(GLenum target, GLenum pname, const GLfloat * params)
{
    qFatal("glTexParameterfv not implemented");
    Q_UNUSED(target);
    Q_UNUSED(pname);
    Q_UNUSED(params);
}

static void glTexParameteri(GLenum target, GLenum pname, GLint param)
{
    auto event = currentContext()->createEvent(QStringLiteral("texParameteri"));
    if (!event)
        return;
    event->addInt(target);
    event->addInt(pname);
    event->addInt(param);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glTexParameteriv(GLenum target, GLenum pname, const GLint * params)
{
    qFatal("glTexParameteriv not implemented");
    Q_UNUSED(target);
    Q_UNUSED(pname);
    Q_UNUSED(params);
}

static void glTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset,
                            GLsizei width, GLsizei height, GLenum format, GLenum type,
                            const void * pixels)
{
    auto event = currentContext()->createEvent(QStringLiteral("texSubImage2D"));
    if (!event)
        return;
    event->addInt(target);
    event->addInt(level);
    event->addInt(xoffset);
    event->addInt(yoffset);
    event->addInt(width);
    event->addInt(height);
    event->addInt(format);
    event->addInt(type);
    if (pixels) {
        const int len = imageSize(width, height, format, type, currentContextData()->pixelStorage);
        event->addData(QByteArray((const char *)pixels, len));
    } else {
        event->addNull();
    }
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glUniform1f(GLint location, GLfloat v0)
{
    auto event = currentContext()->createEvent(QStringLiteral("uniform1f"), false);
    if (!event)
        return;
    event->addInt(location);
    event->addFloat(v0);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glUniform1fv(GLint location, GLsizei count, const GLfloat * value)
{
    auto event = currentContext()->createEvent(QStringLiteral("uniform1fv"));
    if (!event)
        return;
    event->addInt(location);
    event->addInt(count);
    for (int i = 0; i < count; ++i)
        event->addFloat(value[i]);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glUniform1i(GLint location, GLint v0)
{
    auto event = currentContext()->createEvent(QStringLiteral("uniform1i"));
    if (!event)
        return;
    event->addInt(location);
    event->addInt(v0);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glUniform1iv(GLint location, GLsizei count, const GLint * value)
{
    auto event = currentContext()->createEvent(QStringLiteral("uniform1iv"));
    if (!event)
        return;
    event->addInt(location);
    event->addInt(count);
    for (int i = 0; i < count; ++i)
        event->addInt(value[i]);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glUniform2f(GLint location, GLfloat v0, GLfloat v1)
{
    auto event = currentContext()->createEvent(QStringLiteral("uniform2f"));
    if (!event)
        return;
    event->addInt(location);
    event->addFloat(v0);
    event->addFloat(v1);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glUniform2fv(GLint location, GLsizei count, const GLfloat * value)
{
    auto event = currentContext()->createEvent(QStringLiteral("uniform2fv"));
    if (!event)
        return;
    event->addInt(location);
    event->addInt(count);
    for (int i = 0; i < 2 * count; ++i)
        event->addFloat(value[i]);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glUniform2i(GLint location, GLint v0, GLint v1)
{
    auto event = currentContext()->createEvent(QStringLiteral("uniform2i"));
    if (!event)
        return;
    event->addInt(location);
    event->addInt(v0);
    event->addInt(v1);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glUniform2iv(GLint location, GLsizei count, const GLint * value)
{
    auto event = currentContext()->createEvent(QStringLiteral("uniform2iv"));
    if (!event)
        return;
    event->addInt(location);
    event->addInt(count);
    for (int i = 0; i < 2 * count; ++i)
        event->addInt(value[i]);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glUniform3f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2)
{
    auto event = currentContext()->createEvent(QStringLiteral("uniform3f"));
    if (!event)
        return;
    event->addInt(location);
    event->addFloat(v0);
    event->addFloat(v1);
    event->addFloat(v2);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glUniform3fv(GLint location, GLsizei count, const GLfloat * value)
{
    auto event = currentContext()->createEvent(QStringLiteral("uniform3fv"));
    if (!event)
        return;
    event->addInt(location);
    event->addInt(count);
    for (int i = 0; i < 3 * count; ++i)
        event->addFloat(value[i]);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glUniform3i(GLint location, GLint v0, GLint v1, GLint v2)
{
    auto event = currentContext()->createEvent(QStringLiteral("uniform3i"));
    if (!event)
        return;
    event->addInt(location);
    event->addInt(v0);
    event->addInt(v1);
    event->addInt(v2);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glUniform3iv(GLint location, GLsizei count, const GLint * value)
{
    auto event = currentContext()->createEvent(QStringLiteral("uniform3iv"));
    if (!event)
        return;
    event->addInt(location);
    event->addInt(count);
    for (int i = 0; i < 3 * count; ++i)
        event->addInt(value[i]);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glUniform4f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3)
{
    auto event = currentContext()->createEvent(QStringLiteral("uniform4f"));
    if (!event)
        return;
    event->addInt(location);
    event->addFloat(v0);
    event->addFloat(v1);
    event->addFloat(v2);
    event->addFloat(v3);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glUniform4fv(GLint location, GLsizei count, const GLfloat * value)
{
    auto event = currentContext()->createEvent(QStringLiteral("uniform4fv"));
    if (!event)
        return;
    event->addInt(location);
    event->addInt(count);
    for (int i = 0; i < 4 * count; ++i)
        event->addFloat(value[i]);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glUniform4i(GLint location, GLint v0, GLint v1, GLint v2, GLint v3)
{
    auto event = currentContext()->createEvent(QStringLiteral("uniform4i"));
    if (!event)
        return;
    event->addInt(location);
    event->addInt(v0);
    event->addInt(v1);
    event->addInt(v2);
    event->addInt(v3);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glUniform4iv(GLint location, GLsizei count, const GLint * value)
{
    auto event = currentContext()->createEvent(QStringLiteral("uniform4iv"));
    if (!event)
        return;
    event->addInt(location);
    event->addInt(count);
    for (int i = 0; i < 4 * count; ++i)
        event->addInt(value[i]);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glUniformMatrix2fv(GLint location, GLsizei count, GLboolean transpose,
                               const GLfloat * value)
{
    auto event = currentContext()->createEvent(QStringLiteral("uniformMatrix2fv"));
    if (!event)
        return;
    event->addInt(location);
    event->addInt(count);
    event->addInt(transpose);
    for (int i = 0; i < 4 * count; ++i)
        event->addFloat(value[i]);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glUniformMatrix3fv(GLint location, GLsizei count, GLboolean transpose,
                               const GLfloat * value)
{
    auto event = currentContext()->createEvent(QStringLiteral("uniformMatrix3fv"));
    if (!event)
        return;
    event->addInt(location);
    event->addInt(count);
    event->addInt(transpose);
    for (int i = 0; i < 9 * count; ++i)
        event->addFloat(value[i]);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glUniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose,
                               const GLfloat * value)
{
    auto event = currentContext()->createEvent(QStringLiteral("uniformMatrix4fv"));
    if (!event)
        return;
    event->addInt(location);
    event->addInt(count);
    event->addInt(transpose);
    for (int i = 0; i < 16 * count; ++i)
        event->addFloat(value[i]);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glUseProgram(GLuint program)
{
    auto event = currentContext()->createEvent(QStringLiteral("useProgram"));
    if (!event)
        return;
    event->addUInt(program);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    currentContextData()->currentProgram = program;
}

static void glValidateProgram(GLuint program)
{
    auto event = currentContext()->createEvent(QStringLiteral("validateProgram"));
    if (!event)
        return;
    event->addUInt(program);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glVertexAttrib1f(GLuint index, GLfloat x)
{
    auto event = currentContext()->createEvent(QStringLiteral("vertexAttrib1f"));
    if (!event)
        return;
    event->addUInt(index);
    event->addFloat(x);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glVertexAttrib1fv(GLuint index, const GLfloat * v)
{
    auto event = currentContext()->createEvent(QStringLiteral("vertexAttrib1fv"));
    if (!event)
        return;
    event->addUInt(index);
    event->addFloat(v[0]);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glVertexAttrib2f(GLuint index, GLfloat x, GLfloat y)
{
    auto event = currentContext()->createEvent(QStringLiteral("vertexAttrib2f"));
    if (!event)
        return;
    event->addUInt(index);
    event->addFloat(x);
    event->addFloat(y);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glVertexAttrib2fv(GLuint index, const GLfloat * v)
{
    auto event = currentContext()->createEvent(QStringLiteral("vertexAttrib2fv"));
    if (!event)
        return;
    event->addUInt(index);
    event->addFloat(v[0]);
    event->addFloat(v[1]);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glVertexAttrib3f(GLuint index, GLfloat x, GLfloat y, GLfloat z)
{
    auto event = currentContext()->createEvent(QStringLiteral("vertexAttrib3f"));
    if (!event)
        return;
    event->addUInt(index);
    event->addFloat(x);
    event->addFloat(y);
    event->addFloat(z);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glVertexAttrib3fv(GLuint index, const GLfloat * v)
{
    auto event = currentContext()->createEvent(QStringLiteral("vertexAttrib3fv"));
    if (!event)
        return;
    event->addUInt(index);
    event->addFloat(v[0]);
    event->addFloat(v[1]);
    event->addFloat(v[2]);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glVertexAttrib4f(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
{
    auto event = currentContext()->createEvent(QStringLiteral("vertexAttrib4f"));
    if (!event)
        return;
    event->addUInt(index);
    event->addFloat(x);
    event->addFloat(y);
    event->addFloat(z);
    event->addFloat(w);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glVertexAttrib4fv(GLuint index, const GLfloat * v)
{
    auto event = currentContext()->createEvent(QStringLiteral("vertexAttrib4fv"));
    if (!event)
        return;
    event->addUInt(index);
    event->addFloat(v[0]);
    event->addFloat(v[1]);
    event->addFloat(v[2]);
    event->addFloat(v[3]);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glVertexAttribPointer(GLuint index, GLint size, GLenum type, GLboolean normalized,
                                  GLsizei stride, const void * pointer)
{
    ContextData *d = currentContextData();
    ContextData::VertexAttrib &va(d->vertexAttribPointers[index]);
    va.arrayBufferBinding = d->boundArrayBuffer;
    va.size = size;
    va.type = type;
    va.normalized = normalized;
    va.stride = stride;
    va.pointer = (void *) pointer;

    if (d->boundArrayBuffer) {
        auto event = currentContext()->createEvent(QStringLiteral("vertexAttribPointer"), false);
        if (!event)
            return;
        event->addUInt(index);
        event->addInt(size);
        event->addInt(type);
        event->addInt(normalized);
        event->addInt(stride);
        event->addUInt((quintptr) pointer);
        QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    }
}

static void glViewport(GLint x, GLint y, GLsizei width, GLsizei height)
{
    auto event = currentContext()->createEvent(QStringLiteral("viewport"));
    if (!event)
        return;
    event->addInt(x);
    event->addInt(y);
    event->addInt(width);
    event->addInt(height);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);

    auto it = currentContextData()->cachedParameters.find(GL_VIEWPORT);
    if (it != currentContextData()->cachedParameters.end())
        it->setValue(QVariantList{ x, y, width, height });
}

static void glBlitFramebufferEXT(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
                                 GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
                                 GLbitfield mask, GLenum filter)
{
    auto event = currentContext()->createEvent(QStringLiteral("blitFramebufferEXT"));
    if (!event)
        return;
    event->addInt(srcX0);
    event->addInt(srcY0);
    event->addInt(srcX1);
    event->addInt(srcY1);
    event->addInt(dstX0);
    event->addInt(dstY0);
    event->addInt(dstX1);
    event->addInt(dstY1);
    event->addUInt(mask);
    event->addInt(filter);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glRenderbufferStorageMultisampleEXT(GLenum target, GLsizei samples,
                                                GLenum internalformat, GLsizei width,
                                                GLsizei height)
{
    auto event = currentContext()->createEvent(
                QStringLiteral("renderbufferStorageMultisampleEXT"));
    if (!event)
        return;
    event->addInt(target);
    event->addInt(samples);
    event->addInt(internalformat);
    event->addInt(width);
    event->addInt(height);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

static void glGetTexLevelParameteriv(GLenum target, GLint level, GLenum pname, GLint *params)
{
    qFatal("glGetTexLevelParameteriv not supported");
    Q_UNUSED(target);
    Q_UNUSED(level);
    Q_UNUSED(pname);
    Q_UNUSED(params);
}

}

class QWebGLContextPrivate
{
public:
    int id = -1;
    static QAtomicInt nextId;
    static QSet<int> waitingIds;
    QPlatformSurface *currentSurface = nullptr;
    QSurfaceFormat surfaceFormat;
};

QAtomicInt QWebGLContextPrivate::nextId(1);
QSet<int> QWebGLContextPrivate::waitingIds;

QWebGLContext::QWebGLContext(const QSurfaceFormat &format) :
    d_ptr(new QWebGLContextPrivate)
{
    Q_D(QWebGLContext);
    d->id = d->nextId.fetchAndAddOrdered(1);

    qCDebug(lc, "Creating context %d", d->id);
    d->surfaceFormat = format;
    d->surfaceFormat.setRenderableType(QSurfaceFormat::OpenGLES);
}

QWebGLContext::~QWebGLContext()
{}

QSurfaceFormat QWebGLContext::format() const
{
    Q_D(const QWebGLContext);
    return d->surfaceFormat;
}

void QWebGLContext::swapBuffers(QPlatformSurface *surface)
{
    Q_UNUSED(surface);
    auto event = currentContext()->createEvent(QStringLiteral("swapBuffers"), true);
    if (!event)
        return;
    lockMutex();
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    waitCondition(1000);
    unlockMutex();
}

bool QWebGLContext::makeCurrent(QPlatformSurface *surface)
{
    Q_D(QWebGLContext);

    qCDebug(lc, "%p", surface);
    if (surface->surface()->surfaceClass() == QSurface::Window) {
        const auto window = static_cast<QWebGLWindow *>(surface);
        if (window->winId() == WId(-1))
            return false;
    }

    auto context = QOpenGLContext::currentContext();
    Q_ASSERT(context);
    auto handle = static_cast<QWebGLContext *>(context->handle());
    handle->d_func()->currentSurface = surface;
    auto event = currentContext()->createEvent(QStringLiteral("makeCurrent"));
    if (!event)
        return false;
    event->addInt(d->id);
    if (surface->surface()->surfaceClass() == QSurface::Window) {
        auto window = static_cast<QWebGLWindow *>(surface);
        if (s_contextData[handle->id()].cachedParameters.isEmpty()) {
            auto future = window->d_func()->defaults.get_future();
            std::future_status status = std::future_status::timeout;
            while (status == std::future_status::timeout) {
                if (!QWebGLIntegrationPrivate::instance()->findClientData(surface))
                    return false;
                status = future.wait_for(std::chrono::milliseconds(100));
            }
            s_contextData[handle->id()].cachedParameters  = future.get();
        }
        event->addInt(window->window()->width());
        event->addInt(window->window()->height());
        event->addInt(window->winId());
    } else if (surface->surface()->surfaceClass() == QSurface::Offscreen) {
        qCDebug(lc, "QWebGLContext::makeCurrent: QSurface::Offscreen not implemented");
    }
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
    return true;
}

void QWebGLContext::doneCurrent()
{
    auto event = currentContext()->createEvent(QStringLiteral("makeCurrent"));
    if (!event)
        return;
    event->addInt(0);
    event->addInt(0);
    event->addInt(0);
    event->addInt(0);
    QCoreApplication::postEvent(QWebGLIntegrationPrivate::instance()->webSocketServer, event);
}

bool QWebGLContext::isValid() const
{
    Q_D(const QWebGLContext);
    return d->id != -1;
}

QFunctionPointer QWebGLContext::getProcAddress(const char *procName)
{
    using namespace QWebGL;

    struct FuncTab {
        const char *name;
        QFunctionPointer func;
    } funcTab[] = {
#define QWEBGLCONTEXT_ADD_FUNCTION(NAME) { #NAME, (QFunctionPointer) QWebGL::NAME }
        QWEBGLCONTEXT_ADD_FUNCTION(glActiveTexture),
        QWEBGLCONTEXT_ADD_FUNCTION(glAttachShader),
        QWEBGLCONTEXT_ADD_FUNCTION(glBindAttribLocation),
        QWEBGLCONTEXT_ADD_FUNCTION(glBindBuffer),
        QWEBGLCONTEXT_ADD_FUNCTION(glBindFramebuffer),
        QWEBGLCONTEXT_ADD_FUNCTION(glBindRenderbuffer),
        QWEBGLCONTEXT_ADD_FUNCTION(glBindTexture),
        QWEBGLCONTEXT_ADD_FUNCTION(glBlendColor),
        QWEBGLCONTEXT_ADD_FUNCTION(glBlendEquation),
        QWEBGLCONTEXT_ADD_FUNCTION(glBlendEquationSeparate),
        QWEBGLCONTEXT_ADD_FUNCTION(glBlendFunc),
        QWEBGLCONTEXT_ADD_FUNCTION(glBlendFuncSeparate),
        QWEBGLCONTEXT_ADD_FUNCTION(glBufferData),
        QWEBGLCONTEXT_ADD_FUNCTION(glBufferSubData),
        QWEBGLCONTEXT_ADD_FUNCTION(glCheckFramebufferStatus),
        QWEBGLCONTEXT_ADD_FUNCTION(glClear),
        QWEBGLCONTEXT_ADD_FUNCTION(glClearColor),
        QWEBGLCONTEXT_ADD_FUNCTION(glClearDepthf),
        QWEBGLCONTEXT_ADD_FUNCTION(glClearStencil),
        QWEBGLCONTEXT_ADD_FUNCTION(glColorMask),
        QWEBGLCONTEXT_ADD_FUNCTION(glCompileShader),
        QWEBGLCONTEXT_ADD_FUNCTION(glCompressedTexImage2D),
        QWEBGLCONTEXT_ADD_FUNCTION(glCompressedTexSubImage2D),
        QWEBGLCONTEXT_ADD_FUNCTION(glCopyTexImage2D),
        QWEBGLCONTEXT_ADD_FUNCTION(glCopyTexSubImage2D),
        QWEBGLCONTEXT_ADD_FUNCTION(glCreateProgram),
        QWEBGLCONTEXT_ADD_FUNCTION(glCreateShader),
        QWEBGLCONTEXT_ADD_FUNCTION(glCullFace),
        QWEBGLCONTEXT_ADD_FUNCTION(glDeleteBuffers),
        QWEBGLCONTEXT_ADD_FUNCTION(glDeleteFramebuffers),
        QWEBGLCONTEXT_ADD_FUNCTION(glDeleteProgram),
        QWEBGLCONTEXT_ADD_FUNCTION(glDeleteRenderbuffers),
        QWEBGLCONTEXT_ADD_FUNCTION(glDeleteShader),
        QWEBGLCONTEXT_ADD_FUNCTION(glDeleteTextures),
        QWEBGLCONTEXT_ADD_FUNCTION(glDepthFunc),
        QWEBGLCONTEXT_ADD_FUNCTION(glDepthMask),
        QWEBGLCONTEXT_ADD_FUNCTION(glDepthRangef),
        QWEBGLCONTEXT_ADD_FUNCTION(glDetachShader),
        QWEBGLCONTEXT_ADD_FUNCTION(glDisable),
        QWEBGLCONTEXT_ADD_FUNCTION(glDisableVertexAttribArray),
        QWEBGLCONTEXT_ADD_FUNCTION(glDrawArrays),
        QWEBGLCONTEXT_ADD_FUNCTION(glDrawElements),
        QWEBGLCONTEXT_ADD_FUNCTION(glEnable),
        QWEBGLCONTEXT_ADD_FUNCTION(glEnableVertexAttribArray),
        QWEBGLCONTEXT_ADD_FUNCTION(glFinish),
        QWEBGLCONTEXT_ADD_FUNCTION(glFlush),
        QWEBGLCONTEXT_ADD_FUNCTION(glFramebufferRenderbuffer),
        QWEBGLCONTEXT_ADD_FUNCTION(glFramebufferTexture2D),
        QWEBGLCONTEXT_ADD_FUNCTION(glFrontFace),
        QWEBGLCONTEXT_ADD_FUNCTION(glGenBuffers),
        QWEBGLCONTEXT_ADD_FUNCTION(glGenFramebuffers),
        QWEBGLCONTEXT_ADD_FUNCTION(glGenRenderbuffers),
        QWEBGLCONTEXT_ADD_FUNCTION(glGenTextures),
        QWEBGLCONTEXT_ADD_FUNCTION(glGenerateMipmap),
        QWEBGLCONTEXT_ADD_FUNCTION(glGetActiveAttrib),
        QWEBGLCONTEXT_ADD_FUNCTION(glGetActiveUniform),
        QWEBGLCONTEXT_ADD_FUNCTION(glGetAttachedShaders),
        QWEBGLCONTEXT_ADD_FUNCTION(glGetAttribLocation),
        QWEBGLCONTEXT_ADD_FUNCTION(glGetBooleanv),
        QWEBGLCONTEXT_ADD_FUNCTION(glGetBufferParameteriv),
        QWEBGLCONTEXT_ADD_FUNCTION(glGetError),
        QWEBGLCONTEXT_ADD_FUNCTION(glGetFloatv),
        QWEBGLCONTEXT_ADD_FUNCTION(glGetFramebufferAttachmentParameteriv),
        QWEBGLCONTEXT_ADD_FUNCTION(glGetIntegerv),
        QWEBGLCONTEXT_ADD_FUNCTION(glGetProgramInfoLog),
        QWEBGLCONTEXT_ADD_FUNCTION(glGetProgramiv),
        QWEBGLCONTEXT_ADD_FUNCTION(glGetRenderbufferParameteriv),
        QWEBGLCONTEXT_ADD_FUNCTION(glGetShaderInfoLog),
        QWEBGLCONTEXT_ADD_FUNCTION(glGetShaderPrecisionFormat),
        QWEBGLCONTEXT_ADD_FUNCTION(glGetShaderSource),
        QWEBGLCONTEXT_ADD_FUNCTION(glGetShaderiv),
        QWEBGLCONTEXT_ADD_FUNCTION(glGetString),
        QWEBGLCONTEXT_ADD_FUNCTION(glGetTexParameterfv),
        QWEBGLCONTEXT_ADD_FUNCTION(glGetTexParameteriv),
        QWEBGLCONTEXT_ADD_FUNCTION(glGetUniformLocation),
        QWEBGLCONTEXT_ADD_FUNCTION(glGetUniformfv),
        QWEBGLCONTEXT_ADD_FUNCTION(glGetUniformiv),
        QWEBGLCONTEXT_ADD_FUNCTION(glGetVertexAttribPointerv),
        QWEBGLCONTEXT_ADD_FUNCTION(glGetVertexAttribfv),
        QWEBGLCONTEXT_ADD_FUNCTION(glGetVertexAttribiv),
        QWEBGLCONTEXT_ADD_FUNCTION(glHint),
        QWEBGLCONTEXT_ADD_FUNCTION(glIsBuffer),
        QWEBGLCONTEXT_ADD_FUNCTION(glIsEnabled),
        QWEBGLCONTEXT_ADD_FUNCTION(glIsFramebuffer),
        QWEBGLCONTEXT_ADD_FUNCTION(glIsProgram),
        QWEBGLCONTEXT_ADD_FUNCTION(glIsRenderbuffer),
        QWEBGLCONTEXT_ADD_FUNCTION(glIsShader),
        QWEBGLCONTEXT_ADD_FUNCTION(glIsTexture),
        QWEBGLCONTEXT_ADD_FUNCTION(glLineWidth),
        QWEBGLCONTEXT_ADD_FUNCTION(glLinkProgram),
        QWEBGLCONTEXT_ADD_FUNCTION(glPixelStorei),
        QWEBGLCONTEXT_ADD_FUNCTION(glPolygonOffset),
        QWEBGLCONTEXT_ADD_FUNCTION(glReadPixels),
        QWEBGLCONTEXT_ADD_FUNCTION(glReleaseShaderCompiler),
        QWEBGLCONTEXT_ADD_FUNCTION(glRenderbufferStorage),
        QWEBGLCONTEXT_ADD_FUNCTION(glSampleCoverage),
        QWEBGLCONTEXT_ADD_FUNCTION(glScissor),
        QWEBGLCONTEXT_ADD_FUNCTION(glShaderBinary),
        QWEBGLCONTEXT_ADD_FUNCTION(glShaderSource),
        QWEBGLCONTEXT_ADD_FUNCTION(glStencilFunc),
        QWEBGLCONTEXT_ADD_FUNCTION(glStencilFuncSeparate),
        QWEBGLCONTEXT_ADD_FUNCTION(glStencilMask),
        QWEBGLCONTEXT_ADD_FUNCTION(glStencilMaskSeparate),
        QWEBGLCONTEXT_ADD_FUNCTION(glStencilOp),
        QWEBGLCONTEXT_ADD_FUNCTION(glStencilOpSeparate),
        QWEBGLCONTEXT_ADD_FUNCTION(glTexImage2D),
        QWEBGLCONTEXT_ADD_FUNCTION(glTexParameterf),
        QWEBGLCONTEXT_ADD_FUNCTION(glTexParameterfv),
        QWEBGLCONTEXT_ADD_FUNCTION(glTexParameteri),
        QWEBGLCONTEXT_ADD_FUNCTION(glTexParameteriv),
        QWEBGLCONTEXT_ADD_FUNCTION(glTexSubImage2D),
        QWEBGLCONTEXT_ADD_FUNCTION(glUniform1f),
        QWEBGLCONTEXT_ADD_FUNCTION(glUniform1fv),
        QWEBGLCONTEXT_ADD_FUNCTION(glUniform1i),
        QWEBGLCONTEXT_ADD_FUNCTION(glUniform1iv),
        QWEBGLCONTEXT_ADD_FUNCTION(glUniform2f),
        QWEBGLCONTEXT_ADD_FUNCTION(glUniform2fv),
        QWEBGLCONTEXT_ADD_FUNCTION(glUniform2i),
        QWEBGLCONTEXT_ADD_FUNCTION(glUniform2iv),
        QWEBGLCONTEXT_ADD_FUNCTION(glUniform3f),
        QWEBGLCONTEXT_ADD_FUNCTION(glUniform3fv),
        QWEBGLCONTEXT_ADD_FUNCTION(glUniform3i),
        QWEBGLCONTEXT_ADD_FUNCTION(glUniform3iv),
        QWEBGLCONTEXT_ADD_FUNCTION(glUniform4f),
        QWEBGLCONTEXT_ADD_FUNCTION(glUniform4fv),
        QWEBGLCONTEXT_ADD_FUNCTION(glUniform4i),
        QWEBGLCONTEXT_ADD_FUNCTION(glUniform4iv),
        QWEBGLCONTEXT_ADD_FUNCTION(glUniformMatrix2fv),
        QWEBGLCONTEXT_ADD_FUNCTION(glUniformMatrix3fv),
        QWEBGLCONTEXT_ADD_FUNCTION(glUniformMatrix4fv),
        QWEBGLCONTEXT_ADD_FUNCTION(glUseProgram),
        QWEBGLCONTEXT_ADD_FUNCTION(glValidateProgram),
        QWEBGLCONTEXT_ADD_FUNCTION(glVertexAttrib1f),
        QWEBGLCONTEXT_ADD_FUNCTION(glVertexAttrib1fv),
        QWEBGLCONTEXT_ADD_FUNCTION(glVertexAttrib2f),
        QWEBGLCONTEXT_ADD_FUNCTION(glVertexAttrib2fv),
        QWEBGLCONTEXT_ADD_FUNCTION(glVertexAttrib3f),
        QWEBGLCONTEXT_ADD_FUNCTION(glVertexAttrib3fv),
        QWEBGLCONTEXT_ADD_FUNCTION(glVertexAttrib4f),
        QWEBGLCONTEXT_ADD_FUNCTION(glVertexAttrib4fv),
        QWEBGLCONTEXT_ADD_FUNCTION(glVertexAttribPointer),
        QWEBGLCONTEXT_ADD_FUNCTION(glViewport),
        QWEBGLCONTEXT_ADD_FUNCTION(glBlitFramebufferEXT),
        QWEBGLCONTEXT_ADD_FUNCTION(glRenderbufferStorageMultisampleEXT),
        QWEBGLCONTEXT_ADD_FUNCTION(glGetTexLevelParameteriv)
#undef QWEBGLCONTEXT_ADD_FUNCTION
    };


    auto size = sizeof(funcTab) / sizeof(FuncTab);
    for (auto i = 0u; i < size; ++i)
        if (strcmp(procName, funcTab[i].name) == 0)
            return funcTab[i].func;
    return nullptr;
}

int QWebGLContext::id() const
{
    Q_D(const QWebGLContext);
    return d->id;
}

QPlatformSurface *QWebGLContext::currentSurface() const
{
    Q_D(const QWebGLContext);
    return d->currentSurface;
}

QWebGLFunctionCall *QWebGLContext::createEvent(const QString &functionName, bool wait)
{
    auto context = QOpenGLContext::currentContext();
    Q_ASSERT(context);
    const auto handle = static_cast<QWebGLContext *>(context->handle());
    auto integrationPrivate = QWebGLIntegrationPrivate::instance();
    const auto clientData = integrationPrivate->findClientData(handle->currentSurface());
    if (!clientData || !clientData->socket
            || clientData->socket->state() != QAbstractSocket::ConnectedState)
        return nullptr;
    const auto pointer = new QWebGLFunctionCall(functionName, handle->currentSurface(), wait);
    if (pointer) {
        if (wait)
            QWebGLContextPrivate::waitingIds.insert(pointer->id());
    } else {
        qCWarning(lc, "Cannot create the event, the client is disconnected");
    }

    return pointer;
}

QVariant QWebGLContext::queryValue(int id)
{
    if (!QWebGLContextPrivate::waitingIds.contains(id)) {
        qCWarning(lc, "Unexpected id (%d)", id);
        return QVariant();
    }

    static auto queryValue = [](int id)
    {
        lockMutex();
        waitCondition(10);
        unlockMutex();
        return QWebGLIntegrationPrivate::instance()->webSocketServer->queryValue(id);
    };

    const auto handle = static_cast<QWebGLContext *>(currentContext()->context()->handle());
    QVariant variant = queryValue(id);
    while (variant.isNull()) {
        auto integrationPrivate = QWebGLIntegrationPrivate::instance();
        const auto clientData = integrationPrivate->findClientData(handle->currentSurface());
        if (!clientData || !clientData->socket
                || clientData->socket->state() != QAbstractSocket::ConnectedState)
            return QVariant();
        variant = queryValue(id);
    }
    QWebGLContextPrivate::waitingIds.remove(id);
    return variant;
}

QT_END_NAMESPACE