summaryrefslogtreecommitdiffstats
path: root/src/jogl/classes/com/jogamp/opengl/FBObject.java
blob: c845b46ad6cf0a491c0d71e05544289606310346 (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
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
/**
 * Copyright 2012 JogAmp Community. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice, this list of
 *       conditions and the following disclaimer.
 *
 *    2. Redistributions in binary form must reproduce the above copyright notice, this list
 *       of conditions and the following disclaimer in the documentation and/or other materials
 *       provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * The views and conclusions contained in the software and documentation are those of the
 * authors and should not be interpreted as representing official policies, either expressed
 * or implied, of JogAmp Community.
 */

package com.jogamp.opengl;

import java.util.Arrays;

import javax.media.opengl.GL;
import javax.media.opengl.GL2ES2;
import javax.media.opengl.GL2ES3;
import javax.media.opengl.GL2GL3;
import javax.media.opengl.GL3;
import javax.media.opengl.GLBase;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLContext;
import javax.media.opengl.GLException;
import javax.media.opengl.GLProfile;

import jogamp.opengl.Debug;

import com.jogamp.common.util.PropertyAccess;
import com.jogamp.opengl.FBObject.Attachment.Type;

/**
 * Core utility class simplifying usage of framebuffer objects (FBO)
 * with all {@link GLProfile}s.
 * <p>
 * Supports on-the-fly reconfiguration of dimension and multisample buffers via {@link #reset(GL, int, int, int, boolean)}
 * while preserving the {@link Attachment} references.
 * </p>
 * <p>
 * Integrates default read/write framebuffers via {@link GLContext#getDefaultReadFramebuffer()} and {@link GLContext#getDefaultReadFramebuffer()},
 * which is being hooked at {@link GL#glBindFramebuffer(int, int)} when the default (<code>zero</code>) framebuffer is selected.
 * </p>
 *
 * <p>FIXME: Implement support for {@link Type#DEPTH_TEXTURE}, {@link Type#STENCIL_TEXTURE} .</p>
 */
public class FBObject {
    protected static final boolean DEBUG;
    private static final int USER_MAX_TEXTURE_SIZE;
    private static final boolean FBOResizeQuirk = false;

    static {
        Debug.initSingleton();
        DEBUG = Debug.debug("FBObject");
        USER_MAX_TEXTURE_SIZE = PropertyAccess.getIntProperty("jogl.debug.FBObject.MaxTextureSize", true, 0);
    }

    private static enum DetachAction { NONE, DISPOSE, RECREATE };

    /**
     * Generic color buffer FBO attachment, either of type {@link ColorAttachment} or {@link TextureAttachment}.
     * <p>Always an instance of {@link Attachment}.</p>
     */
    public static interface Colorbuffer {
        /**
         * Initializes the color buffer and set it's parameter, if uninitialized, i.e. name is <code>zero</code>.
         * @return <code>true</code> if newly initialized, otherwise <code>false</code>.
         * @throws GLException if buffer generation or setup fails. The just created buffer name will be deleted in this case.
         */
        boolean initialize(final GL gl) throws GLException;

        /**
         * Releases the color buffer if initialized, i.e. name is not <code>zero</code>.
         * @throws GLException if buffer release fails.
         */
        void free(final GL gl) throws GLException;

        /**
         * Writes the internal format to the given GLCapabilities object.
         * @param caps the destination for format bits
         * @param rgba8Avail whether rgba8 is available
         */
        void formatToGLCapabilities(final GLCapabilities caps, final boolean rgba8Avail);

        /**
         * Returns <code>true</code> if instance is of type {@link TextureAttachment}
         * and <code>false</code> if instance is of type {@link ColorAttachment}.
         */
        boolean isTextureAttachment();

        /**
         * Casts this object to a {@link TextureAttachment} reference, see {@link #isTextureAttachment()}.
         * @throws GLException if this object is not of type {@link TextureAttachment}
         * @see #isTextureAttachment()
         */
        TextureAttachment getTextureAttachment();

        /**
         * Casts this object to a {@link ColorAttachment} reference, see {@link #isTextureAttachment()}.
         * @throws GLException if this object is not of type {@link ColorAttachment}
         * @see #isTextureAttachment()
         */
        ColorAttachment getColorAttachment();

        /** internal format of colorbuffer */
        int getFormat();

        /** width of colorbuffer */
        int getWidth();

        /** height of colorbuffer */
        int getHeight();

        /** colorbuffer name [1..max] */
        int getName();
    }

    /** Common super class of all FBO attachments */
    public static abstract class Attachment {
        public enum Type {
            NONE, DEPTH, STENCIL, DEPTH_STENCIL, COLOR, COLOR_TEXTURE, DEPTH_TEXTURE, STENCIL_TEXTURE;

            /**
             * Returns {@link #COLOR}, {@link #DEPTH}, {@link #STENCIL} or {@link #DEPTH_STENCIL}
             * @throws IllegalArgumentException if <code>format</code> cannot be handled.
             */
            public static Type determine(final int format) throws IllegalArgumentException {
                switch(format) {
                    case GL.GL_RGBA4:
                    case GL.GL_RGB5_A1:
                    case GL.GL_RGB565:
                    case GL.GL_RGB8:
                    case GL.GL_RGBA8:
                        return Type.COLOR;
                    case GL.GL_DEPTH_COMPONENT16:
                    case GL.GL_DEPTH_COMPONENT24:
                    case GL.GL_DEPTH_COMPONENT32:
                        return Type.DEPTH;
                    case GL.GL_STENCIL_INDEX1:
                    case GL.GL_STENCIL_INDEX4:
                    case GL.GL_STENCIL_INDEX8:
                        return Type.STENCIL;
                    case GL.GL_DEPTH24_STENCIL8:
                        return Type.DEPTH_STENCIL;
                    default:
                        throw new IllegalArgumentException("format invalid: "+toHexString(format));
                }
            }
        };

        /** immutable type [{@link #COLOR}, {@link #DEPTH}, {@link #STENCIL}, {@link #COLOR_TEXTURE}, {@link #DEPTH_TEXTURE}, {@link #STENCIL_TEXTURE} ] */
        public final Type type;

        /** immutable the internal format */
        public final int format;

        private int width, height;

        private int name;

        protected Attachment(final Type type, final int iFormat, final int width, final int height, final int name) {
            this.type = type;
            this.format = iFormat;
            this.width = width;
            this.height = height;
            this.name = name;
        }

        /**
         * Writes the internal format to the given GLCapabilities object.
         * @param caps the destination for format bits
         * @param rgba8Avail whether rgba8 is available
         */
        public final void formatToGLCapabilities(final GLCapabilities caps, final boolean rgba8Avail) {
            final int _format;
            switch(format) {
                case GL.GL_RGBA:
                case 4:
                    _format = rgba8Avail ? GL.GL_RGBA8 : GL.GL_RGBA4;
                    break;
                case GL.GL_RGB:
                case 3:
                    _format = rgba8Avail ? GL.GL_RGB8 : GL.GL_RGB565;
                    break;
                default:
                    _format = format;
            }
            switch(_format) {
                case GL.GL_RGBA4:
                    caps.setRedBits(4);
                    caps.setGreenBits(4);
                    caps.setBlueBits(4);
                    caps.setAlphaBits(4);
                    break;
                case GL.GL_RGB5_A1:
                    caps.setRedBits(5);
                    caps.setGreenBits(5);
                    caps.setBlueBits(5);
                    caps.setAlphaBits(1);
                    break;
                case GL.GL_RGB565:
                    caps.setRedBits(5);
                    caps.setGreenBits(6);
                    caps.setBlueBits(5);
                    caps.setAlphaBits(0);
                    break;
                case GL.GL_RGB8:
                    caps.setRedBits(8);
                    caps.setGreenBits(8);
                    caps.setBlueBits(8);
                    caps.setAlphaBits(0);
                    break;
                case GL.GL_RGBA8:
                    caps.setRedBits(8);
                    caps.setGreenBits(8);
                    caps.setBlueBits(8);
                    caps.setAlphaBits(8);
                    break;
                case GL.GL_DEPTH_COMPONENT16:
                    caps.setDepthBits(16);
                    break;
                case GL.GL_DEPTH_COMPONENT24:
                    caps.setDepthBits(24);
                    break;
                case GL.GL_DEPTH_COMPONENT32:
                    caps.setDepthBits(32);
                    break;
                case GL.GL_STENCIL_INDEX1:
                    caps.setStencilBits(1);
                    break;
                case GL.GL_STENCIL_INDEX4:
                    caps.setStencilBits(4);
                    break;
                case GL.GL_STENCIL_INDEX8:
                    caps.setStencilBits(8);
                    break;
                case GL.GL_DEPTH24_STENCIL8:
                    caps.setDepthBits(24);
                    caps.setStencilBits(8);
                    break;
                default:
                    throw new IllegalArgumentException("format invalid: "+toHexString(format));
            }
        }

        /** immutable internal format of attachment */
        public final int getFormat() { return format; }

        /** width of attachment */
        public final int getWidth() { return width; }
        /** height of attachment */
        public final int getHeight() { return height; }
        /* pp */ final void setSize(final int w, final int h) { width = w; height = h; }

        /** buffer name [1..max], maybe a texture or renderbuffer name, depending on type. */
        public final int getName() { return name; }
        /* pp */ final void setName(final int n) { name = n; }

        /**
         * Initializes the attachment and set it's parameter, if uninitialized, i.e. name is <code>zero</code>.
         * <pre>
            final boolean init = 0 == name;
            if( init ) {
                do init ..
            }
            return init;
         * </pre>
         * @return <code>true</code> if newly initialized, otherwise <code>false</code>.
         * @throws GLException if buffer generation or setup fails. The just created buffer name will be deleted in this case.
         */
        public abstract boolean initialize(final GL gl) throws GLException;

        /**
         * Releases the attachment if initialized, i.e. name is not <code>zero</code>.
         * <pre>
            if(0 != name) {
                do free ..
                name = 0;
            }
         * </pre>
         * @throws GLException if buffer release fails.
         */
        public abstract void free(final GL gl) throws GLException;

        /**
         * <p>
         * Comparison by {@link #type}, {@link #format}, {@link #width}, {@link #height} and {@link #name}.
         * </p>
         * {@inheritDoc}
         */
        @Override
        public boolean equals(final Object o) {
            if( this == o ) return true;
            if( ! ( o instanceof Attachment ) ) return false;
            final Attachment a = (Attachment)o;
            return type == a.type &&
                   format == a.format &&
                   width == a.width   &&
                   height== a.height  &&
                   name == a.name     ;
        }

        /**
         * <p>
         * Hashed by {@link #type}, {@link #format}, {@link #width}, {@link #height} and {@link #name}.
         * </p>
         * {@inheritDoc}
         */
        @Override
        public int hashCode() {
            // 31 * x == (x << 5) - x
            int hash = 31 + type.ordinal();
            hash = ((hash << 5) - hash) + format;
            hash = ((hash << 5) - hash) + width;
            hash = ((hash << 5) - hash) + height;
            hash = ((hash << 5) - hash) + name;
            return hash;
        }

        int objectHashCode() { return super.hashCode(); }

        @Override
        public String toString() {
            return getClass().getSimpleName()+"[type "+type+", format "+toHexString(format)+", "+width+"x"+height+
                   "; name "+toHexString(name)+", obj "+toHexString(objectHashCode())+"]";
        }

        public static Type getType(final int attachmentPoint, final int maxColorAttachments) {
            if( GL.GL_COLOR_ATTACHMENT0 <= attachmentPoint && attachmentPoint < GL.GL_COLOR_ATTACHMENT0+maxColorAttachments ) {
                return Type.COLOR;
            }
            switch(attachmentPoint) {
                case GL.GL_DEPTH_ATTACHMENT:
                    return Type.DEPTH;
                case GL.GL_STENCIL_ATTACHMENT:
                    return Type.STENCIL;
                default:
                    throw new IllegalArgumentException("Invalid attachment point "+toHexString(attachmentPoint));
            }
        }
    }

    /** Other renderbuffer attachment which maybe a colorbuffer, depth or stencil. */
    public static class RenderAttachment extends Attachment {
        private int samples;

        /**
         * @param type allowed types are {@link Type#DEPTH_STENCIL} {@link Type#DEPTH}, {@link Type#STENCIL} or {@link Type#COLOR}
         * @param iFormat
         * @param samples
         * @param width
         * @param height
         * @param name
         */
        public RenderAttachment(final Type type, final int iFormat, final int samples, final int width, final int height, final int name) {
            super(validateType(type), iFormat, width, height, name);
            this.samples = samples;
        }

        /** number of samples, or zero for no multisampling */
        public final int getSamples() { return samples; }
        /* pp */ final void setSamples(final int s) { samples = s; }

        private static Type validateType(final Type type) {
            switch(type) {
                case DEPTH_STENCIL:
                case DEPTH:
                case STENCIL:
                case COLOR:
                    return type;
                default:
                    throw new IllegalArgumentException("Invalid type: "+type);
            }
        }

        /**
         * <p>
         * Comparison by {@link #type}, {@link #format}, {@link #samples}, {@link #width}, {@link #height} and {@link #name}.
         * </p>
         * {@inheritDoc}
         */
        @Override
        public boolean equals(final Object o) {
            if( this == o ) return true;
            if( ! ( o instanceof RenderAttachment ) ) return false;
            return super.equals(o) &&
                   samples == ((RenderAttachment)o).samples;
        }

        /**
         * <p>
         * Hashed by {@link #type}, {@link #format}, {@link #samples}, {@link #width}, {@link #height} and {@link #name}.
         * </p>
         * {@inheritDoc}
         */
        @Override
        public int hashCode() {
            // 31 * x == (x << 5) - x
            int hash = super.hashCode();
            hash = ((hash << 5) - hash) + samples;
            return hash;
        }

        @Override
        public boolean initialize(final GL gl) throws GLException {
            final boolean init = 0 == getName();
            if( init ) {
                checkPreGLError(gl);

                final int[] name = new int[] { -1 };
                gl.glGenRenderbuffers(1, name, 0);
                setName(name[0]);

                gl.glBindRenderbuffer(GL.GL_RENDERBUFFER, getName());
                if( samples > 0 ) {
                    ((GL2ES3)gl).glRenderbufferStorageMultisample(GL.GL_RENDERBUFFER, samples, format, getWidth(), getHeight());
                } else {
                    gl.glRenderbufferStorage(GL.GL_RENDERBUFFER, format, getWidth(), getHeight());
                }
                final int glerr = gl.glGetError();
                if(GL.GL_NO_ERROR != glerr) {
                    gl.glDeleteRenderbuffers(1, name, 0);
                    setName(0);
                    throw new GLException("GL Error "+toHexString(glerr)+" while creating "+this);
                }
                if(DEBUG) {
                    System.err.println("Attachment.init.X: "+this);
                }
            }
            return init;
        }

        @Override
        public void free(final GL gl) {
            final int[] name = new int[] { getName() };
            if( 0 != name[0] ) {
                if(DEBUG) {
                    System.err.println("Attachment.free.0: "+this);
                }
                gl.glDeleteRenderbuffers(1, name, 0);
                setName(0);
            }
        }

        @Override
        public String toString() {
            return getClass().getSimpleName()+"[type "+type+", format "+toHexString(format)+", samples "+samples+", "+getWidth()+"x"+getHeight()+
                   ", name "+toHexString(getName())+", obj "+toHexString(objectHashCode())+"]";
        }
    }

    /** Color render buffer FBO attachment  */
    public static class ColorAttachment extends RenderAttachment implements Colorbuffer {
        public ColorAttachment(final int iFormat, final int samples, final int width, final int height, final int name) {
            super(Type.COLOR, iFormat, samples, width, height, name);
        }
        @Override
        public final boolean isTextureAttachment() { return false; }
        @Override
        public final TextureAttachment getTextureAttachment() { throw new GLException("Not a TextureAttachment, but ColorAttachment"); }
        @Override
        public final ColorAttachment getColorAttachment() { return this; }

    }

    /** Texture FBO attachment */
    public static class TextureAttachment extends Attachment implements Colorbuffer  {
        /** details of the texture setup */
        public final int dataFormat, dataType, magFilter, minFilter, wrapS, wrapT;

        /**
         * @param type allowed types are [ {@link Type#COLOR_TEXTURE}, {@link Type#DEPTH_TEXTURE}, {@link Type#STENCIL_TEXTURE} ]
         * @param iFormat
         * @param width
         * @param height
         * @param dataFormat
         * @param dataType
         * @param magFilter
         * @param minFilter
         * @param wrapS
         * @param wrapT
         * @param name
         */
        public TextureAttachment(final Type type, final int iFormat, final int width, final int height, final int dataFormat, final int dataType,
                                 final int magFilter, final int minFilter, final int wrapS, final int wrapT, final int name) {
            super(validateType(type), iFormat, width, height, name);
            this.dataFormat = dataFormat;
            this.dataType = dataType;
            this.magFilter = magFilter;
            this.minFilter = minFilter;
            this.wrapS = wrapS;
            this.wrapT = wrapT;
        }

        private static Type validateType(final Type type) {
            switch(type) {
                case COLOR_TEXTURE:
                case DEPTH_TEXTURE:
                case STENCIL_TEXTURE:
                    return type;
                default:
                    throw new IllegalArgumentException("Invalid type: "+type);
            }
        }

        /**
         * Initializes the texture and set it's parameter, if uninitialized, i.e. name is <code>zero</code>.
         * @throws GLException if texture generation and setup fails. The just created texture name will be deleted in this case.
         */
        @Override
        public boolean initialize(final GL gl) throws GLException {
            final boolean init = 0 == getName();
            if( init ) {
                checkPreGLError(gl);

                final int[] name = new int[] { -1 };
                gl.glGenTextures(1, name, 0);
                if(0 == name[0]) {
                    throw new GLException("null texture, "+this);
                }
                setName(name[0]);

                gl.glBindTexture(GL.GL_TEXTURE_2D, name[0]);
                if( 0 < magFilter ) {
                    gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, magFilter);
                }
                if( 0 < minFilter ) {
                    gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, minFilter);
                }
                if( 0 < wrapS ) {
                    gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, wrapS);
                }
                if( 0 < wrapT ) {
                    gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, wrapT);
                }
                boolean preTexImage2D = true;
                int glerr = gl.glGetError();
                if(GL.GL_NO_ERROR == glerr) {
                    preTexImage2D = false;
                    gl.glTexImage2D(GL.GL_TEXTURE_2D, 0, format, getWidth(), getHeight(), 0, dataFormat, dataType, null);
                    glerr = gl.glGetError();
                }
                if(GL.GL_NO_ERROR != glerr) {
                    gl.glDeleteTextures(1, name, 0);
                    setName(0);
                    throw new GLException("GL Error "+toHexString(glerr)+" while creating (pre TexImage2D "+preTexImage2D+") "+this);
                }
                if(DEBUG) {
                    System.err.println("Attachment.init.X: "+this);
                }
            }
            return init;
        }

        @Override
        public void free(final GL gl) {
            final int[] name = new int[] { getName() };
            if( 0 != name[0] ) {
                if(DEBUG) {
                    System.err.println("Attachment.free.0: "+this);
                }
                gl.glDeleteTextures(1, name, 0);
                setName(0);
            }
        }

        @Override
        public final boolean isTextureAttachment() { return true; }
        @Override
        public final TextureAttachment getTextureAttachment() { return this; }
        @Override
        public final ColorAttachment getColorAttachment() { throw new GLException("Not a ColorAttachment, but TextureAttachment"); }

        @Override
        public String toString() {
            return getClass().getSimpleName()+"[type "+type+", target GL_TEXTURE_2D, level 0, format "+toHexString(format)+
                                              ", "+getWidth()+"x"+getHeight()+", border 0, dataFormat "+toHexString(dataFormat)+
                                              ", dataType "+toHexString(dataType)+
                                              "; min/mag "+toHexString(minFilter)+"/"+toHexString(magFilter)+
                                              ", wrap S/T "+toHexString(wrapS)+"/"+toHexString(wrapT)+
                                              "; name "+toHexString(getName())+", obj "+toHexString(objectHashCode())+"]";
        }
    }
    static String toHexString(final int v) {
        return "0x"+Integer.toHexString(v);
    }

    /**
     * Creates a color {@link TextureAttachment}, i.e. type {@link Type#COLOR_TEXTURE},
     * selecting the texture data type and format automatically.
     *
     * <p>Using default min/mag filter {@link GL#GL_NEAREST} and default wrapS/wrapT {@link GL#GL_CLAMP_TO_EDGE}.</p>
     *
     * @param gl the used {@link GLContext}'s {@link GL} object
     * @param alpha set to <code>true</code> if you request alpha channel, otherwise <code>false</code>;
     * @param width texture width
     * @param height texture height
     * @return the created and uninitialized color {@link TextureAttachment}
     */
    public static final TextureAttachment createColorTextureAttachment(final GL gl, final boolean alpha, final int width, final int height) {
        return createColorTextureAttachment(gl, alpha, width, height, GL.GL_NEAREST, GL.GL_NEAREST, GL.GL_CLAMP_TO_EDGE, GL.GL_CLAMP_TO_EDGE);
    }

    /**
     * Creates a color {@link TextureAttachment}, i.e. type {@link Type#COLOR_TEXTURE},
     * selecting the texture data type and format automatically.
     * <p>
     * For GLES3, sampling-sink format <b>must be equal</b> w/ the sampling-source {@link Colorbuffer},
     * see details below. Implementation aligns w/ {@link #createColorAttachment(boolean)}
     * and is enforced via {@link #sampleSinkExFormatMismatch(GL)}.
     * </p>
     * <p>
     * ES3 BlitFramebuffer Requirements: OpenGL ES 3.0.2 p194: 4.3.2  Copying Pixels
     * <pre>
     * If SAMPLE_BUFFERS for the read framebuffer is greater than zero, no copy
     * is performed and an INVALID_OPERATION error is generated if the formats of
     * the read and draw framebuffers are not identical or if the source and destination
     * rectangles are not defined with the same (X0, Y 0) and (X1, Y 1) bounds.
     * </pre>
     * Texture and Renderbuffer format details:
     * <pre>
     * ES2 Base iFormat: OpenGL ES 2.0.24 p66: 3.7.1 Texture Image Specification, Table 3.8
     *   ALPHA, LUMINANCE, LUMINANCE_ALPHA, RGB, RGBA
     *
     * ES3 Base iFormat: OpenGL ES 3.0.2 p125: 3.8.3 Texture Image Specification, Table 3.11
     *   ALPHA, LUMINANCE, LUMINANCE_ALPHA, RGB, RGBA
     *   DEPTH_COMPONENT, STENCIL_COMPONENT, RED, RG
     *
     * ES3 Required Texture and Renderbuffer iFormat: OpenGL ES 3.0.2 p126: 3.8.3 Texture Image Specification
     *   - RGBA32I, RGBA32UI, RGBA16I, RGBA16UI, RGBA8, RGBA8I,
     *     RGBA8UI, SRGB8_ALPHA8, RGB10_A2, RGB10_A2UI, RGBA4, and
     *     RGB5_A1.
     *   - RGB8 and RGB565.
     *   - RG32I, RG32UI, RG16I, RG16UI, RG8, RG8I, and RG8UI.
     *   - R32I, R32UI, R16I, R16UI, R8, R8I, and R8UI.
     * </pre>
     * </p>
     *
     * @param gl the used {@link GLContext}'s {@link GL} object
     * @param alpha set to <code>true</code> if you request alpha channel, otherwise <code>false</code>;
     * @param width texture width
     * @param height texture height
     * @param magFilter if > 0 value for {@link GL#GL_TEXTURE_MAG_FILTER}
     * @param minFilter if > 0 value for {@link GL#GL_TEXTURE_MIN_FILTER}
     * @param wrapS if > 0 value for {@link GL#GL_TEXTURE_WRAP_S}
     * @param wrapT if > 0 value for {@link GL#GL_TEXTURE_WRAP_T}
     * @return the created and uninitialized color {@link TextureAttachment}
     */
    public static final TextureAttachment createColorTextureAttachment(final GL gl, final boolean alpha, final int width, final int height,
                                                                       final int magFilter, final int minFilter, final int wrapS, final int wrapT) {
        final int internalFormat, dataFormat, dataType;
        if(gl.isGLES3()) {
            internalFormat = alpha ? GL.GL_RGBA8 : GL.GL_RGB8;
            dataFormat = alpha ? GL.GL_RGBA : GL.GL_RGB;
            dataType = GL.GL_UNSIGNED_BYTE;
        } else if(gl.isGLES()) {
            internalFormat = alpha ? GL.GL_RGBA : GL.GL_RGB;
            dataFormat = alpha ? GL.GL_RGBA : GL.GL_RGB;
            dataType = GL.GL_UNSIGNED_BYTE;
        } else {
            internalFormat = alpha ? GL.GL_RGBA8 : GL.GL_RGB8;
            // textureInternalFormat = alpha ? GL.GL_RGBA : GL.GL_RGB;
            // textureInternalFormat = alpha ? 4 : 3;
            dataFormat = alpha ? GL.GL_BGRA : GL.GL_RGB;
            dataType = alpha ? GL2GL3.GL_UNSIGNED_INT_8_8_8_8_REV : GL.GL_UNSIGNED_BYTE;
        }
        return createColorTextureAttachment(internalFormat, width, height, dataFormat, dataType, magFilter, minFilter, wrapS, wrapT);
    }

    public static final TextureAttachment createColorTextureAttachment(final GL gl, final int internalFormat, final int width, final int height,
                                                                       final int magFilter, final int minFilter, final int wrapS, final int wrapT) {
        final int dataFormat, dataType;
        final boolean alpha = hasAlpha(internalFormat);
        if( gl.isGLES3() ) {
            dataFormat = alpha ? GL.GL_RGBA : GL.GL_RGB;
            dataType = GL.GL_UNSIGNED_BYTE;
        } else if( gl.isGLES() ) {
            dataFormat = alpha ? GL.GL_RGBA : GL.GL_RGB;
            dataType = GL.GL_UNSIGNED_BYTE;
        } else {
            dataFormat = alpha ? GL.GL_BGRA : GL.GL_RGB;
            dataType = alpha ? GL2GL3.GL_UNSIGNED_INT_8_8_8_8_REV : GL.GL_UNSIGNED_BYTE;
        }
        return createColorTextureAttachment(internalFormat, width, height, dataFormat, dataType, magFilter, minFilter, wrapS, wrapT);
    }

    /**
     * Creates a color {@link TextureAttachment}, i.e. type {@link Type#COLOR_TEXTURE}.
     *
     * @param internalFormat internalFormat parameter to {@link GL#glTexImage2D(int, int, int, int, int, int, int, int, long)}
     * @param width texture width
     * @param height texture height
     * @param dataFormat format parameter to {@link GL#glTexImage2D(int, int, int, int, int, int, int, int, long)}
     * @param dataType type parameter to {@link GL#glTexImage2D(int, int, int, int, int, int, int, int, long)}
     * @param magFilter if > 0 value for {@link GL#GL_TEXTURE_MAG_FILTER}
     * @param minFilter if > 0 value for {@link GL#GL_TEXTURE_MIN_FILTER}
     * @param wrapS if > 0 value for {@link GL#GL_TEXTURE_WRAP_S}
     * @param wrapT if > 0 value for {@link GL#GL_TEXTURE_WRAP_T}
     * @return the created and uninitialized color {@link TextureAttachment}
     */
    public static final TextureAttachment createColorTextureAttachment(final int internalFormat, final int width, final int height, final int dataFormat, final int dataType,
                                                                       final int magFilter, final int minFilter, final int wrapS, final int wrapT) {
        return new TextureAttachment(Type.COLOR_TEXTURE, internalFormat, width, height, dataFormat, dataType,
                                     magFilter, minFilter, wrapS, wrapT, 0 /* name */);
    }

    private static boolean hasAlpha(final int format) {
        switch(format) {
            case GL.GL_RGBA8:
            case GL.GL_RGBA4:
            case GL.GL_RGBA:
            case GL.GL_BGRA:
            case 4:
                return true;
            default:
                return false;
        }
    }

    private boolean initialized;
    private boolean fullFBOSupport;
    private boolean rgba8Avail;
    private boolean depth24Avail;
    private boolean depth32Avail;
    private boolean stencil01Avail;
    private boolean stencil04Avail;
    private boolean stencil08Avail;
    private boolean stencil16Avail;
    private boolean packedDepthStencilAvail;
    private int maxColorAttachments, maxSamples, maxTextureSize, maxRenderbufferSize;

    private int width, height, samples;
    private int vStatus;
    private boolean ignoreStatus;
    private int fbName;
    private boolean bound;

    private int colorbufferCount;
    private int textureAttachmentCount;
    private Colorbuffer[] colorbufferAttachments; // colorbuffer attachment points
    private RenderAttachment depth, stencil; // depth and stencil maybe equal in case of packed-depth-stencil
    private boolean modified; // size, sampleCount, or any attachment modified

    private FBObject samplingSink; // MSAA sink
    private Colorbuffer samplingColorSink;
    private boolean samplingSinkDirty;

    //
    // ColorAttachment helper ..
    //

    private final void validateColorAttachmentPointRange(final int point) {
        if(!initialized) {
            throw new GLException("FBO not initialized");
        }
        if(maxColorAttachments != colorbufferAttachments.length) {
            throw new InternalError(String.format("maxColorAttachments %d, array.length %d",
                                                   maxColorAttachments, colorbufferAttachments.length) );
        }
        if(0 > point || point >= maxColorAttachments) {
            throw new IllegalArgumentException(String.format("attachment point out of range: %d, should be within [0..%d], %s",
                                                              point, maxColorAttachments-1, this.toString() ) );
        }
    }

    private final void validateAddColorAttachment(final int point, final Colorbuffer ca) {
        validateColorAttachmentPointRange(point);
        if( null != colorbufferAttachments[point] ) {
            throw new IllegalStateException(String.format("Cannot attach %s at %d, attachment point already in use by %s, %s",
                    ca.toString(), point, colorbufferAttachments[point].toString(), this.toString() ) );
        }
    }

    private final void addColorAttachment(final int point, final Colorbuffer ca, final boolean validate) {
        final Colorbuffer c = colorbufferAttachments[point];
        if( validate ) {
            validateColorAttachmentPointRange(point);
            if( null == ca ) {
                throw new IllegalArgumentException("Colorbuffer is null");
            }
            if( null != c ) {
                throw new IllegalStateException(String.format("Cannot attach %s at %d, attachment point already in use by %s, %s",
                                                              ca.toString(), point, c.toString(), this.toString() ) );
            }
        }
        colorbufferAttachments[point] = ca;
        colorbufferCount++;
        if( ca.isTextureAttachment() ) {
            textureAttachmentCount++;
        }
        modified = true;
    }

    private final void removeColorAttachment(final int point, final Colorbuffer ca) {
        validateColorAttachmentPointRange(point);
        if( null == ca ) {
            throw new IllegalArgumentException("Colorbuffer is null");
        }
        final Colorbuffer c = colorbufferAttachments[point];
        if( c != ca ) {
            throw new IllegalStateException(String.format("Cannot detach %s at %d, slot is holding other: %s, %s",
                                                          ca.toString(), point, c.toString(), this.toString() ) );
        }
        colorbufferAttachments[point] = null;
        colorbufferCount--;
        if( ca.isTextureAttachment() ) {
            textureAttachmentCount--;
        }
        modified = true;
    }

    /**
     * Return the {@link Colorbuffer} attachment at <code>attachmentPoint</code> if it is attached to this FBO, otherwise null.
     *
     * @see #attachColorbuffer(GL, boolean)
     * @see #attachColorbuffer(GL, boolean)
     * @see #attachTexture2D(GL, int, boolean, int, int, int, int)
     * @see #attachTexture2D(GL, int, int, int, int, int, int, int, int)
     */
    public final Colorbuffer getColorbuffer(final int attachmentPoint) {
        validateColorAttachmentPointRange(attachmentPoint);
        return colorbufferAttachments[attachmentPoint];
    }

    /**
     * Finds the passed {@link Colorbuffer} within the valid range of attachment points
     * using <i>reference</i> comparison only.
     * <p>
     * Note: Slow. Implementation uses a logN array search to save resources, i.e. not using a HashMap.
     * </p>
     * @param ca the {@link Colorbuffer} to look for.
     * @return -1 if the {@link Colorbuffer} could not be found, otherwise [0..{@link #getMaxColorAttachments()}-1]
     */
    public final int getColorbufferAttachmentPoint(final Colorbuffer ca) {
        for(int i=0; i<colorbufferAttachments.length; i++) {
            if( colorbufferAttachments[i] == ca ) {
                return i;
            }
        }
        return -1;
    }

    /**
     * Returns the passed {@link Colorbuffer} if it is attached to this FBO, otherwise null.
     * Implementation compares the <i>reference</i> only.
     *
     * <p>
     * Note: Slow. Uses {@link #getColorbufferAttachmentPoint(Colorbuffer)} to determine it's attachment point
     *       to be used for {@link #getColorbuffer(int)}
     * </p>
     *
     * @see #attachColorbuffer(GL, boolean)
     * @see #attachColorbuffer(GL, boolean)
     * @see #attachTexture2D(GL, int, boolean, int, int, int, int)
     * @see #attachTexture2D(GL, int, int, int, int, int, int, int, int)
     */
    public final Colorbuffer getColorbuffer(final Colorbuffer ca) {
        final int p = getColorbufferAttachmentPoint(ca);
        return p>=0 ? getColorbuffer(p) : null;
    }

    /**
     * Returns true if any attached {@link Colorbuffer} uses alpha,
     * otherwise false.
     */
    public final boolean hasAttachmentUsingAlpha() {
        final int caCount = getColorbufferCount();
        boolean hasAlpha = false;
        for(int i=0; i<caCount; i++) {
            final Attachment ca = (Attachment)getColorbuffer(i);
            if( null == ca ) {
                break;
            }
            if( hasAlpha(ca.format) ) {
                hasAlpha = true;
                break;
            }
        }
        return hasAlpha;
    }

    /**
     * Creates an uninitialized FBObject instance.
     * <p>
     * Call {@link #init(GL, int, int, int)} .. etc to use it.
     * </p>
     */
    public FBObject() {
        this.initialized = false;

        // TBD @ init
        this.fullFBOSupport = false;
        this.rgba8Avail = false;
        this.depth24Avail = false;
        this.depth32Avail = false;
        this.stencil01Avail = false;
        this.stencil04Avail = false;
        this.stencil08Avail = false;
        this.stencil16Avail = false;
        this.packedDepthStencilAvail = false;
        this.maxColorAttachments=-1;
        this.maxSamples=-1;
        this.maxTextureSize = 0;
        this.maxRenderbufferSize = 0;

        this.width = 0;
        this.height = 0;
        this.samples = 0;
        this.vStatus = -1;
        this.ignoreStatus = false;
        this.fbName = 0;
        this.bound = false;

        this.colorbufferAttachments = null; // at init ..
        this.colorbufferCount = 0;
        this.textureAttachmentCount = 0;
        this.depth = null;
        this.stencil = null;
        this.modified = true;

        this.samplingSink = null;
        this.samplingColorSink = null;
        this.samplingSinkDirty = true;
    }

    /**
     * Initializes this FBO's instance.
     * <p>
     * The sampling sink is not initializes, allowing manual assignment via {@link #setSamplingSink(FBObject)}
     * if {@code newSamples > 0}.
     * </p>
     *
     * <p>Leaves the FBO bound</p>
     *
     * @param gl the current GL context
     * @param newWidth the initial width, it's minimum is capped to 1
     * @param newHeight the initial height, it's minimum is capped to 1
     * @param newSamples if > 0, MSAA will be used, otherwise no multisampling. Will be capped to {@link #getMaxSamples()}.
     * @throws IllegalStateException if already initialized
     * @throws GLException in case of an error, i.e. size too big, etc ..
     */
    public void init(final GL gl, final int newWidth, final int newHeight, final int newSamples) throws IllegalStateException, GLException {
        if( initialized ) {
            throw new IllegalStateException("FBO already initialized");
        }
        if( !gl.hasBasicFBOSupport() ) {
            throw new GLException("FBO not supported w/ context: "+gl.getContext()+", "+this);
        }
        fullFBOSupport = gl.hasFullFBOSupport();

        rgba8Avail = gl.isGL2ES3() || gl.isExtensionAvailable(GLExtensions.OES_rgb8_rgba8);
        depth24Avail = fullFBOSupport || gl.isExtensionAvailable(GLExtensions.OES_depth24);
        depth32Avail = fullFBOSupport || gl.isExtensionAvailable(GLExtensions.OES_depth32);
        stencil01Avail = fullFBOSupport || gl.isExtensionAvailable(GLExtensions.OES_stencil1);
        stencil04Avail = fullFBOSupport || gl.isExtensionAvailable(GLExtensions.OES_stencil4);
        stencil08Avail = fullFBOSupport || gl.isExtensionAvailable(GLExtensions.OES_stencil8);
        stencil16Avail = fullFBOSupport;

        packedDepthStencilAvail = fullFBOSupport ||
                                  gl.isExtensionAvailable(GLExtensions.OES_packed_depth_stencil) ||
                                  gl.isExtensionAvailable(GLExtensions.EXT_packed_depth_stencil) ;

        final boolean NV_fbo_color_attachments = gl.isExtensionAvailable(GLExtensions.NV_fbo_color_attachments);

        final int val[] = new int[1];

        checkPreGLError(gl);

        int realMaxColorAttachments = 1;
        maxColorAttachments = 1;
        if( fullFBOSupport || NV_fbo_color_attachments ) {
            try {
                val[0] = 0;
                gl.glGetIntegerv(GL2ES2.GL_MAX_COLOR_ATTACHMENTS, val, 0);
                realMaxColorAttachments = 1 <= val[0] ? val[0] : 1; // cap minimum to 1
            } catch (final GLException gle) { gle.printStackTrace(); }
        }
        maxColorAttachments = realMaxColorAttachments <= 8 ? realMaxColorAttachments : 8; // cap to limit array size

        colorbufferAttachments = new Colorbuffer[maxColorAttachments];
        colorbufferCount = 0;
        textureAttachmentCount = 0;

        maxSamples = gl.getMaxRenderbufferSamples(); // if > 0 implies fullFBOSupport
        gl.glGetIntegerv(GL.GL_MAX_TEXTURE_SIZE, val, 0);
        final int _maxTextureSize = val[0];
        if( 0 < USER_MAX_TEXTURE_SIZE ) {
            maxTextureSize = USER_MAX_TEXTURE_SIZE;
        } else {
            maxTextureSize = _maxTextureSize;
        }
        gl.glGetIntegerv(GL.GL_MAX_RENDERBUFFER_SIZE, val, 0);
        maxRenderbufferSize = val[0];

        checkPreGLError(gl);

        this.width = 0 < newWidth ? newWidth : 1;
        this.height = 0 < newHeight ? newHeight : 1;
        this.samples = newSamples <= maxSamples ? newSamples : maxSamples;

        if(DEBUG) {
            System.err.println("FBObject.init() START: "+width+"x"+height+", "+newSamples+" -> "+this.samples+" samples");
            System.err.println("fullFBOSupport:           "+fullFBOSupport);
            System.err.println("maxColorAttachments:      "+maxColorAttachments+"/"+realMaxColorAttachments+" [capped/real]");
            System.err.println("maxSamples:               "+maxSamples);
            System.err.println("maxTextureSize:           "+_maxTextureSize+" -> "+maxTextureSize);
            System.err.println("maxRenderbufferSize:      "+maxRenderbufferSize);
            System.err.println("rgba8:                    "+rgba8Avail);
            System.err.println("depth24:                  "+depth24Avail);
            System.err.println("depth32:                  "+depth32Avail);
            System.err.println("stencil01:                "+stencil01Avail);
            System.err.println("stencil04:                "+stencil04Avail);
            System.err.println("stencil08:                "+stencil08Avail);
            System.err.println("stencil16:                "+stencil16Avail);
            System.err.println("packedDepthStencil:       "+packedDepthStencilAvail);
            System.err.println("NV_fbo_color_attachments: "+NV_fbo_color_attachments);
            System.err.println(gl.getContext().getGLVersion());
            System.err.println(JoglVersion.getGLStrings(gl, null, false).toString());
        }

        checkNoError(null, gl.glGetError(), "FBObject Init.pre"); // throws GLException if error

        if( width > maxRenderbufferSize || height > maxRenderbufferSize  ) {
            throw new GLException("Size "+width+"x"+height+" exceeds on of the maxima renderbuffer size "+maxRenderbufferSize+": \n\t"+this);
        }

        modified = true;
        samplingSinkDirty = true;

        // generate fbo ..
        gl.glGenFramebuffers(1, val, 0);
        fbName = val[0];
        if(0 == fbName) {
            throw new GLException("null framebuffer");
        }

        // bind fbo ..
        gl.glBindFramebuffer(GL.GL_FRAMEBUFFER, fbName);
        checkNoError(gl, gl.glGetError(), "FBObject Init.bindFB");  // throws GLException if error
        if(!gl.glIsFramebuffer(fbName)) {
            checkNoError(gl, GL.GL_INVALID_VALUE, "FBObject Init.isFB"); // throws GLException
        }
        bound = true;
        initialized = true;

        vStatus = GL.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT; // always incomplete w/o attachments!
        if(DEBUG) {
            System.err.println("FBObject.init() END: "+this);
            Thread.dumpStack();
        }
    }

    /**
     * Resets this FBO's instance.
     * <p>
     * In case the new parameters are compatible with the current ones
     * no action will be performed and method returns immediately.<br>
     * Otherwise all attachments will be recreated
     * to match the new given parameters.
     * </p>
     * <p>
     * {@link #resetSamplingSink(GL)} is being issued immediately
     * to match the new configuration.
     * </p>
     *
     * <p>Leaves the FBO bound state untouched</p>
     *
     * @param gl the current GL context
     * @param newWidth the new width, it's minimum is capped to 1
     * @param newHeight the new height, it's minimum is capped to 1
     * @param newSamples if > 0, MSAA will be used, otherwise no multisampling. Will be capped to {@link #getMaxSamples()}.
     * @return {@code true} if this instance has been modified, otherwise {@code false}.
     * @throws IllegalStateException if not initialized via {@link #init(GL, int, int, int)}.
     * @throws GLException in case of an error, i.e. size too big, etc ..
     */
    public final boolean reset(final GL gl, final int newWidth, final int newHeight, final int newSamples) throws GLException, IllegalStateException {
        if( !initialized ) {
            throw new IllegalStateException("FBO not initialized");
        }
        return reset(gl, newWidth, newHeight, newSamples, true);
    }

    /**
     * Initializes or resets this FBO's instance.
     * <p>
     * In case the new parameters are compatible with the current ones
     * no action will be performed. Otherwise all attachments will be recreated
     * to match the new given parameters.
     * </p>
     *
     * <p>Leaves the FBO bound state untouched</p>
     *
     * @param gl the current GL context
     * @param newWidth
     * @param newHeight
     * @return {@code true} if this instance has been modified, otherwise {@code false}.
     * @throws GLException in case of an error
     * @deprecated Use {@link #init(GL, int, int, int)} or {@link #reset(GL, int, int, int)}
     */
    public final boolean reset(final GL gl, final int newWidth, final int newHeight) {
        return reset(gl, newWidth, newHeight, 0, false);
    }

    /**
     * Initializes or resets this FBO's instance.
     * <p>
     * In case the new parameters are compatible with the current ones
     * no action will be performed. Otherwise all attachments will be recreated
     * to match the new given parameters.
     * </p>
     *
     * <p>Leaves the FBO bound state untouched</p>
     *
     * @param gl the current GL context
     * @param newWidth the new width, it's minimum is capped to 1
     * @param newHeight the new height, it's minimum is capped to 1
     * @param newSamples if > 0, MSAA will be used, otherwise no multisampling. Will be capped to {@link #getMaxSamples()}.
     * @param resetSamplingSink <code>true</code> calls {@link #resetSamplingSink(GL)} immediatly.
     *                          <code>false</code> postpones resetting the sampling sink until {@link #use(GL, TextureAttachment)} or {@link #syncSamplingSink(GL)},
     *                          allowing to use the samples sink's FBO and texture until then. The latter is useful to benefit
     *                          from implicit double buffering while resetting the sink just before it's being used, eg. at swap-buffer.
     * @return {@code true} if this instance has been modified, otherwise {@code false}.
     * @throws GLException in case of an error, i.e. size too big, etc ..
     * @deprecated Use {@link #init(GL, int, int, int)} or {@link #reset(GL, int, int, int)}
     */
    public final boolean reset(final GL gl, int newWidth, int newHeight, int newSamples, final boolean resetSamplingSink) {
        if( !initialized ) {
            init(gl, newWidth, newHeight, newSamples);
            return true;
        }

        newSamples = newSamples <= maxSamples ? newSamples : maxSamples; // clamp

        if( newWidth !=  width || newHeight !=  height || newSamples != samples ) {
            if( 0 >= newWidth )  { newWidth = 1; }
            if( 0 >= newHeight ) { newHeight = 1; }
            if( textureAttachmentCount > 0 && ( newWidth > 2 + maxTextureSize  || newHeight > 2 + maxTextureSize ) ) {
                throw new GLException("Size "+newWidth+"x"+newHeight+" exceeds on of the maximum texture size "+maxTextureSize+": \n\t"+this);
            }
            if( newWidth > maxRenderbufferSize || newHeight > maxRenderbufferSize  ) {
                throw new GLException("Size "+newWidth+"x"+newHeight+" exceeds on of the maxima renderbuffer size "+maxRenderbufferSize+": \n\t"+this);
            }

            if(DEBUG) {
                System.err.println("FBObject.reset - START - "+width+"x"+height+", "+samples+" -> "+newWidth+"x"+newHeight+", "+newSamples+"; "+this);
            }

            final boolean wasBound = isBound();

            final int sampleCountChange;
            if( 0 < samples && 0 < newSamples || 0 == samples && 0 == newSamples ) {
                sampleCountChange =  0; // keep MSAA settings
            } else if( 0 == samples && 0 < newSamples ) {
                sampleCountChange =  1; // add MSAA
            } else if( 0 < samples && 0 == newSamples ) {
                sampleCountChange = -1; // remove MSAA
            } else {
                throw new IllegalArgumentException("Error in sampleCount change: "+samples+" -> "+newSamples);
            }
            width = newWidth;
            height = newHeight;
            samples = newSamples;

            modified = true;
            samplingSinkDirty = true;

            detachAllImpl(gl, true, true, sampleCountChange);
            if( resetSamplingSink ) {
                resetSamplingSink(gl);
            }

            if(!wasBound) {
                unbind(gl);
            }

            if(DEBUG) {
                System.err.println("FBObject.reset - END - wasBound, "+wasBound+", "+this);
            }
            return true;
        } else {
            return false;
        }
    }

    /**
     * Simply resets this instance's size only, w/o validation.
     *
     * <p>Leaves the FBO bound</p>
     *
     * @param gl the current GL context
     * @param newWidth the new width, it's minimum is capped to 1
     * @param newHeight the new height, it's minimum is capped to 1
     */
    private final void resetSizeImpl(final GL gl, final int newWidth, final int newHeight) {
        if(DEBUG) {
            System.err.println("FBObject.resetSize - START - "+width+"x"+height+", "+samples+" -> "+newWidth+"x"+newHeight);
        }

        final int sampleCountChange = 0; // keep MSAA settings
        width = newWidth;
        height = newHeight;

        modified = true;
        samplingSinkDirty = true;

        detachAllImpl(gl, true, true, sampleCountChange);

        if(DEBUG) {
            System.err.println("FBObject.resetSize - END - "+this);
        }
    }

    private void validateAttachmentSize(final Attachment a) {
        final int aWidth = a.getWidth();
        final int aHeight = a.getHeight();

        if( a instanceof TextureAttachment && ( aWidth > 2 + maxTextureSize  || aHeight > 2 + maxTextureSize ) ) {
            throw new GLException("Size "+aWidth+"x"+aHeight+" of "+a+" exceeds on of the maximum texture size "+maxTextureSize+": \n\t"+this);
        }
        if( aWidth > maxRenderbufferSize || aHeight > maxRenderbufferSize  ) {
            throw new GLException("Size "+aWidth+"x"+aHeight+" of "+a+" exceeds on of the maxima renderbuffer size "+maxRenderbufferSize+": \n\t"+this);
        }
    }

    /**
     * Writes the internal format of the attachments to the given GLCapabilities object.
     * @param caps the destination for format bits
     */
    public final void formatToGLCapabilities(final GLCapabilities caps) {
        caps.setSampleBuffers(samples > 0);
        caps.setNumSamples(samples);
        caps.setDepthBits(0);
        caps.setStencilBits(0);

        final Colorbuffer cb = samples > 0 ? getSamplingSink() : getColorbuffer(0);
        if(null != cb) {
            cb.formatToGLCapabilities(caps, rgba8Avail);
        }
        if(null != depth) {
            depth.formatToGLCapabilities(caps, rgba8Avail);
        }
        if(null != stencil && stencil != depth) {
            stencil.formatToGLCapabilities(caps, rgba8Avail);
        }
    }

    /**
     * Note that the status may reflect an incomplete state during transition of attachments.
     * @return The FB status. {@link GL.GL_FRAMEBUFFER_COMPLETE} if ok, otherwise return GL FBO error state or -1
     * @see #validateStatus()
     */
    public final int getStatus() {
        return vStatus;
    }

    /** return the {@link #getStatus()} as a string. */
    public final String getStatusString() {
        return getStatusString(vStatus);
    }

    public static final String getStatusString(final int fbStatus) {
        switch(fbStatus) {
            case -1:
                return "NOT A FBO";

            case GL.GL_FRAMEBUFFER_COMPLETE:
                return "OK";

            case GL.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
                return("FBO incomplete attachment\n");
            case GL.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
                return("FBO missing attachment");
            case GL.GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
                return("FBO attached images must have same dimensions");
            case GL.GL_FRAMEBUFFER_INCOMPLETE_FORMATS:
                 return("FBO attached images must have same format");
            case GL2GL3.GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:
                return("FBO missing draw buffer");
            case GL2GL3.GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
                return("FBO missing read buffer");
            case GL2ES3.GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
                return("FBO missing multisample buffer");
            case GL3.GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS:
                return("FBO missing layer targets");

            case GL.GL_FRAMEBUFFER_UNSUPPORTED:
                return("Unsupported FBO format");
            case GL2ES3.GL_FRAMEBUFFER_UNDEFINED:
                 return("FBO undefined");

            case 0:
                return("FBO implementation fault");
            default:
                return("FBO incomplete, implementation ERROR "+toHexString(fbStatus));
        }
    }

    /**
     * The status may even be valid if incomplete during transition of attachments.
     * @see #getStatus()
     */
    public final boolean isStatusValid() {
        switch(vStatus) {
            case GL.GL_FRAMEBUFFER_COMPLETE:
                return true;

            case GL.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
            case GL.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
            case GL.GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
            case GL.GL_FRAMEBUFFER_INCOMPLETE_FORMATS:
            case GL2GL3.GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:
            case GL2GL3.GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
            case GL2ES3.GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
            case GL3.GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS:
                if(0 == colorbufferCount || null == depth) {
                    // we are in transition
                    return true;
                }

            case GL.GL_FRAMEBUFFER_UNSUPPORTED:
            case GL2ES3.GL_FRAMEBUFFER_UNDEFINED:

            case 0:
            default:
                if(DEBUG) {
                    System.err.println("Framebuffer " + fbName + " is incomplete, status = " + toHexString(vStatus) +
                            " : " + getStatusString(vStatus));
                }
                return false;
        }
    }

    private static int checkPreGLError(final GL gl) {
        final int glerr = gl.glGetError();
        if(DEBUG && GL.GL_NO_ERROR != glerr) {
            System.err.println("Pre-existing GL error: "+toHexString(glerr));
            Thread.dumpStack();
        }
        return glerr;
    }

    private final boolean checkNoError(final GL gl, final int err, final String exceptionMessage) throws GLException {
        if(GL.GL_NO_ERROR != err) {
            if(null != gl) {
                destroy(gl);
            }
            if(null != exceptionMessage) {
                throw new GLException(exceptionMessage+" GL Error "+toHexString(err)+" of "+this.toString());
            }
            return false;
        }
        return true;
    }

    private final void checkInitialized() throws GLException {
        if(!initialized) {
            throw new GLException("FBO not initialized, call init(GL) first.");
        }
    }

    /**
     * Attaches a {@link Colorbuffer}, i.e. {@link TextureAttachment}, to this FBO's instance at the given attachment point,
     * selecting the texture data type and format automatically.
     *
     * <p>Using default min/mag filter {@link GL#GL_NEAREST} and default wrapS/wrapT {@link GL#GL_CLAMP_TO_EDGE}.</p>
     *
     * <p>Leaves the FBO bound.</p>
     *
     * @param gl the current GL context
     * @param attachmentPoint the color attachment point ranging from [0..{@link #getMaxColorAttachments()}-1]
     * @param alpha set to <code>true</code> if you request alpha channel, otherwise <code>false</code>;
     * @return TextureAttachment instance describing the new attached texture colorbuffer if bound and configured successfully, otherwise GLException is thrown
     * @throws GLException in case the texture colorbuffer couldn't be allocated or MSAA has been chosen
     * @see #createColorTextureAttachment(GLProfile, boolean, int, int)
     */
    public final TextureAttachment attachTexture2D(final GL gl, final int attachmentPoint, final boolean alpha) throws GLException {
        return attachColorbuffer(gl, attachmentPoint,
                                 createColorTextureAttachment(gl, alpha, width, height)).getTextureAttachment();
    }

    /**
     * Attaches a {@link Colorbuffer}, i.e. {@link TextureAttachment}, to this FBO's instance at the given attachment point,
     * selecting the texture data type and format automatically.
     *
     * <p>Leaves the FBO bound.</p>
     *
     * @param gl the current GL context
     * @param attachmentPoint the color attachment point ranging from [0..{@link #getMaxColorAttachments()}-1]
     * @param alpha set to <code>true</code> if you request alpha channel, otherwise <code>false</code>;
     * @param magFilter if > 0 value for {@link GL#GL_TEXTURE_MAG_FILTER}
     * @param minFilter if > 0 value for {@link GL#GL_TEXTURE_MIN_FILTER}
     * @param wrapS if > 0 value for {@link GL#GL_TEXTURE_WRAP_S}
     * @param wrapT if > 0 value for {@link GL#GL_TEXTURE_WRAP_T}
     * @return TextureAttachment instance describing the new attached texture colorbuffer if bound and configured successfully, otherwise GLException is thrown
     * @throws GLException in case the texture colorbuffer couldn't be allocated or MSAA has been chosen
     * @see #createColorTextureAttachment(GLProfile, boolean, int, int, int, int, int, int)
     */
    public final TextureAttachment attachTexture2D(final GL gl, final int attachmentPoint, final boolean alpha, final int magFilter, final int minFilter, final int wrapS, final int wrapT) throws GLException {
        return attachColorbuffer(gl, attachmentPoint,
                                 createColorTextureAttachment(gl, alpha, width, height, magFilter, minFilter, wrapS, wrapT)).getTextureAttachment();
    }

    /**
     * Attaches a {@link Colorbuffer}, i.e. {@link TextureAttachment}, to this FBO's instance at the given attachment point.
     *
     * <p>Leaves the FBO bound.</p>
     *
     * @param gl the current GL context
     * @param attachmentPoint the color attachment point ranging from [0..{@link #getMaxColorAttachments()}-1]
     * @param internalFormat internalFormat parameter to {@link GL#glTexImage2D(int, int, int, int, int, int, int, int, long)}
     * @param dataFormat format parameter to {@link GL#glTexImage2D(int, int, int, int, int, int, int, int, long)}
     * @param dataType type parameter to {@link GL#glTexImage2D(int, int, int, int, int, int, int, int, long)}
     * @param magFilter if > 0 value for {@link GL#GL_TEXTURE_MAG_FILTER}
     * @param minFilter if > 0 value for {@link GL#GL_TEXTURE_MIN_FILTER}
     * @param wrapS if > 0 value for {@link GL#GL_TEXTURE_WRAP_S}
     * @param wrapT if > 0 value for {@link GL#GL_TEXTURE_WRAP_T}
     * @return TextureAttachment instance describing the new attached texture colorbuffer if bound and configured successfully, otherwise GLException is thrown
     * @throws GLException in case the texture colorbuffer couldn't be allocated or MSAA has been chosen
     * @see #createColorTextureAttachment(int, int, int, int, int, int, int, int, int)
     */
    public final TextureAttachment attachTexture2D(final GL gl, final int attachmentPoint,
                                                   final int internalFormat, final int dataFormat, final int dataType,
                                                   final int magFilter, final int minFilter, final int wrapS, final int wrapT) throws GLException {
        return attachColorbuffer(gl, attachmentPoint,
                                 createColorTextureAttachment(internalFormat, width, height, dataFormat, dataType, magFilter, minFilter, wrapS, wrapT)).getTextureAttachment();
    }

    /**
     * Creates a {@link ColorAttachment}, selecting the format automatically.
     * <p>
     * For GLES3, sampling-sink {@link Colorbuffer} format <b>must be equal</b> w/ the sampling-source {@link Colorbuffer}.
     * Implementation aligns w/ {@link #createColorTextureAttachment(GLProfile, boolean, int, int, int, int, int, int)}
     * and is enforced via {@link #sampleSinkExFormatMismatch(GL)}.
     * </p>
     *
     * @param alpha set to <code>true</code> if you request alpha channel, otherwise <code>false</code>;
     * @return uninitialized ColorAttachment instance describing the new attached colorbuffer
     */
    public final ColorAttachment createColorAttachment(final boolean alpha) {
        final int internalFormat;

        if( rgba8Avail ) {
            internalFormat = alpha ? GL.GL_RGBA8 : GL.GL_RGB8 ;
        } else {
            internalFormat = alpha ? GL.GL_RGBA4 : GL.GL_RGB565;
        }
        return createColorAttachment(internalFormat, samples, width, height);
    }

    /**
     * Creates a {@link ColorAttachment}, selecting the format automatically.
     * <p>
     * For GLES3, sampling-sink {@link Colorbuffer} format <b>must be equal</b> w/ the sampling-source {@link Colorbuffer}.
     * Implementation aligns w/ {@link #createColorTextureAttachment(GLProfile, boolean, int, int, int, int, int, int)}
     * and is enforced via {@link #sampleSinkExFormatMismatch(GL)}.
     * </p>
     *
     * @param alpha set to <code>true</code> if you request alpha channel, otherwise <code>false</code>;
     * @return uninitialized ColorAttachment instance describing the new attached colorbuffer
     */
    public static final ColorAttachment createColorAttachment(final int internalFormat, final int samples, final int width, final int height) {
        return new ColorAttachment(internalFormat, samples, width, height, 0 /* name not yet determined */);
    }

    public static final RenderAttachment createRenderAttachment(final Type type, final int internalFormat, final int samples, final int width, final int height) {
        return new RenderAttachment(type, internalFormat, samples, width, height, 0 /* name not yet determined */);
    }

    /**
     * Attaches a newly created and {@link Colorbuffer#initialize(GL) initialized} {@link Colorbuffer}, i.e. a {@link ColorAttachment},
     * at the given attachment point.
     * <p>
     * The {@link ColorAttachment} is created using {@code alpha} if {@code true} and current {@code sample count} and {@code size}.
     * </p>
     *
     * <p>Leaves the FBO bound.</p>
     *
     * @param gl the current GL context
     * @param attachmentPoint the color attachment point ranging from [0..{@link #getMaxColorAttachments()}-1]
     * @param alpha set to <code>true</code> if you request alpha channel, otherwise <code>false</code>;
     * @return ColorAttachment instance describing the new attached colorbuffer if bound and configured successfully, otherwise GLException is thrown
     * @throws GLException in case the colorbuffer couldn't be allocated
     * @see #createColorAttachment(boolean)
     */
    public final ColorAttachment attachColorbuffer(final GL gl, final int attachmentPoint, final boolean alpha) throws GLException {
        return attachColorbuffer(gl, attachmentPoint, createColorAttachment(alpha)).getColorAttachment();
    }

    /**
     * Attaches a newly created and {@link Colorbuffer#initialize(GL) initialized} {@link Colorbuffer}, i.e. a {@link ColorAttachment},
     * at the given attachment point.
     * <p>
     * The {@link ColorAttachment} is created using the given {@code internalFormat} and current {@code sample count} and {@code size}.
     * </p>
     *
     * <p>Leaves the FBO bound.</p>
     *
     * @param gl the current GL context
     * @param attachmentPoint the color attachment point ranging from [0..{@link #getMaxColorAttachments()}-1]
     * @param internalFormat usually {@link GL#GL_RGBA4}, {@link GL#GL_RGB5_A1}, {@link GL#GL_RGB565}, {@link GL#GL_RGB8} or {@link GL#GL_RGBA8}
     * @return ColorAttachment instance describing the new attached colorbuffer if bound and configured successfully, otherwise GLException is thrown
     * @throws GLException in case the colorbuffer couldn't be allocated
     * @throws IllegalArgumentException if <code>internalFormat</code> doesn't reflect a colorbuffer
     */
    public final ColorAttachment attachColorbuffer(final GL gl, final int attachmentPoint, final int internalFormat) throws GLException, IllegalArgumentException {
        final Attachment.Type atype = Attachment.Type.determine(internalFormat);
        if( Attachment.Type.COLOR != atype ) {
            throw new IllegalArgumentException("colorformat invalid: "+toHexString(internalFormat)+", "+this);
        }

        return attachColorbuffer(gl, attachmentPoint, createColorAttachment(internalFormat, samples, width, height)).getColorAttachment();
    }

    /**
     * Attaches a {@link Colorbuffer} at the given attachment point
     * and {@link Colorbuffer#initialize(GL) initializes} it, if not done yet.
     * <p>
     * {@link Colorbuffer} may be a {@link ColorAttachment} or {@link TextureAttachment}.
     * </p>
     * <p>
     * If {@link Colorbuffer} is a {@link TextureAttachment} and is uninitialized, i.e. it's texture name is <code>zero</code>,
     * a new texture name is generated and setup w/ the texture parameter.<br/>
     * Otherwise, i.e. texture name is not <code>zero</code>, the passed TextureAttachment <code>texA</code> is
     * considered complete and assumed matching this FBO requirement. A GL error may occur is the latter is untrue.
     * </p>
     *
     * <p>Leaves the FBO bound.</p>
     *
     * @param gl
     * @param attachmentPoint the color attachment point ranging from [0..{@link #getMaxColorAttachments()}-1]
     * @param colbuf the to be attached {@link Colorbuffer}
     * @return given {@link Colorbuffer} instance if bound and configured successfully, otherwise GLException is thrown
     * @throws GLException in case the colorbuffer couldn't be allocated or MSAA has been chosen in case of a {@link TextureAttachment}
     */
    public final Colorbuffer attachColorbuffer(final GL gl, final int attachmentPoint, final Colorbuffer colbuf) throws GLException {
        bind(gl);
        return attachColorbufferImpl(gl, attachmentPoint, colbuf);
    }

    private final Colorbuffer attachColorbufferImpl(final GL gl, final int attachmentPoint, final Colorbuffer colbuf) throws GLException {
        validateAddColorAttachment(attachmentPoint, colbuf);
        validateAttachmentSize((Attachment)colbuf);

        final boolean initializedColorbuf = colbuf.initialize(gl);
        addColorAttachment(attachmentPoint, colbuf, false);

        if( colbuf.isTextureAttachment() ) {
            final TextureAttachment texA = colbuf.getTextureAttachment();
            if( samples > 0 ) {
                removeColorAttachment(attachmentPoint, texA);
                if(initializedColorbuf) {
                    texA.free(gl);
                }
                throw new GLException("Texture2D not supported w/ MSAA. If you have enabled MSAA with exisiting texture attachments, you may want to detach them via detachAllTexturebuffer(gl).");
            }

            // Set up the color buffer for use as a renderable texture:
            gl.glFramebufferTexture2D(GL.GL_FRAMEBUFFER,
                                      GL.GL_COLOR_ATTACHMENT0 + attachmentPoint,
                                      GL.GL_TEXTURE_2D, texA.getName(), 0);

            if(!ignoreStatus) {
                updateStatus(gl);
                if(!isStatusValid()) {
                    detachColorbuffer(gl, attachmentPoint, true);
                    throw new GLException("attachTexture2D "+texA+" at "+attachmentPoint+" failed "+getStatusString()+", "+this);
                }
            }
        } else {
            final ColorAttachment colA = colbuf.getColorAttachment();

            // Attach the color buffer
            gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER,
                                         GL.GL_COLOR_ATTACHMENT0 + attachmentPoint,
                                         GL.GL_RENDERBUFFER, colA.getName());

            if(!ignoreStatus) {
                updateStatus(gl);
                if(!isStatusValid()) {
                    detachColorbuffer(gl, attachmentPoint, true);
                    throw new GLException("attachColorbuffer "+colA+" at "+attachmentPoint+" failed "+getStatusString()+", "+this);
                }
            }
        }
        if(DEBUG) {
            System.err.println("FBObject.attachColorbuffer.X: [attachmentPoint "+attachmentPoint+", colbuf "+colbuf+"]: "+this);
        }
        return colbuf;
    }

    /**
     * Attaches one depth, stencil or packed-depth-stencil buffer to this FBO's instance,
     * selecting the internalFormat automatically.
     * <p>
     * Stencil and depth buffer can be attached only once.
     * </p>
     * <p>
     * In case the desired type or bit-number is not supported, the next available one is chosen.
     * </p>
     * <p>
     * Use {@link #getDepthAttachment()} and/or {@link #getStencilAttachment()} to retrieve details
     * about the attached buffer. The details cannot be returned, since it's possible 2 buffers
     * are being created, depth and stencil.
     * </p>
     *
     * <p>Leaves the FBO bound.</p>
     *
     * @param gl
     * @param atype either {@link Type#DEPTH}, {@link Type#STENCIL} or {@link Type#DEPTH_STENCIL}
     * @param reqBits desired bits for depth or -1 for default (24 bits)
     * @throws GLException in case the renderbuffer couldn't be allocated or one is already attached.
     * @throws IllegalArgumentException
     * @see #getDepthAttachment()
     * @see #getStencilAttachment()
     */
    public final void attachRenderbuffer(final GL gl, final Attachment.Type atype, int reqBits) throws GLException, IllegalArgumentException {
        if( 0 > reqBits ) {
            reqBits = 24;
        }
        final int internalFormat;
        int internalStencilFormat = -1;

        switch ( atype ) {
            case DEPTH:
                if( 32 <= reqBits && depth32Avail ) {
                    internalFormat = GL.GL_DEPTH_COMPONENT32;
                } else if( 24 <= reqBits && depth24Avail ) {
                    internalFormat = GL.GL_DEPTH_COMPONENT24;
                } else {
                    internalFormat = GL.GL_DEPTH_COMPONENT16;
                }
                break;

            case STENCIL:
                if( 16 <= reqBits && stencil16Avail ) {
                    internalFormat = GL2GL3.GL_STENCIL_INDEX16;
                } else if( 8 <= reqBits && stencil08Avail ) {
                    internalFormat = GL.GL_STENCIL_INDEX8;
                } else if( 4 <= reqBits && stencil04Avail ) {
                    internalFormat = GL.GL_STENCIL_INDEX4;
                } else if( 1 <= reqBits && stencil01Avail ) {
                    internalFormat = GL.GL_STENCIL_INDEX1;
                } else {
                    throw new GLException("stencil buffer n/a");
                }
                break;

            case DEPTH_STENCIL:
                if( packedDepthStencilAvail ) {
                    internalFormat = GL.GL_DEPTH24_STENCIL8;
                } else {
                    if( 24 <= reqBits && depth24Avail ) {
                        internalFormat = GL.GL_DEPTH_COMPONENT24;
                    } else {
                        internalFormat = GL.GL_DEPTH_COMPONENT16;
                    }
                    if( stencil08Avail ) {
                        internalStencilFormat = GL.GL_STENCIL_INDEX8;
                    } else if( stencil04Avail ) {
                        internalStencilFormat = GL.GL_STENCIL_INDEX4;
                    } else if( stencil01Avail ) {
                        internalStencilFormat = GL.GL_STENCIL_INDEX1;
                    } else {
                        throw new GLException("stencil buffer n/a");
                    }
                }
                break;
            default:
                throw new IllegalArgumentException("only depth/stencil types allowed, was "+atype+", "+this);
        }

        attachRenderbufferImpl(gl, atype, internalFormat);

        if(0<=internalStencilFormat) {
            attachRenderbufferImpl(gl, Attachment.Type.STENCIL, internalStencilFormat);
        }
    }

    /**
     * Attaches one depth, stencil or packed-depth-stencil buffer to this FBO's instance,
     * depending on the <code>internalFormat</code>.
     * <p>
     * Stencil and depth buffer can be attached only once.
     * </p>
     * <p>
     * Use {@link #getDepthAttachment()} and/or {@link #getStencilAttachment()} to retrieve details
     * about the attached buffer. The details cannot be returned, since it's possible 2 buffers
     * are being created, depth and stencil.
     * </p>
     *
     * <p>Leaves the FBO bound.</p>
     *
     * @param gl the current GL context
     * @param internalFormat {@link GL#GL_DEPTH_COMPONENT16}, {@link GL#GL_DEPTH_COMPONENT24}, {@link GL#GL_DEPTH_COMPONENT32},
     *                       {@link GL#GL_STENCIL_INDEX1}, {@link GL#GL_STENCIL_INDEX4}, {@link GL#GL_STENCIL_INDEX8}
     *                       or {@link GL#GL_DEPTH24_STENCIL8}
     * @throws GLException in case the renderbuffer couldn't be allocated or one is already attached.
     * @throws IllegalArgumentException
     * @see #getDepthAttachment()
     * @see #getStencilAttachment()
     */
    public final void attachRenderbuffer(final GL gl, final int internalFormat) throws GLException, IllegalArgumentException {
        final Attachment.Type atype = Attachment.Type.determine(internalFormat);
        if( Attachment.Type.DEPTH != atype && Attachment.Type.STENCIL != atype && Attachment.Type.DEPTH_STENCIL != atype ) {
            throw new IllegalArgumentException("renderformat invalid: "+toHexString(internalFormat)+", "+this);
        }
        attachRenderbufferImpl(gl, atype, internalFormat);
    }

    protected final void attachRenderbufferImpl(final GL gl, final Attachment.Type atype, final int internalFormat) throws GLException {
        if( null != depth && ( Attachment.Type.DEPTH == atype || Attachment.Type.DEPTH_STENCIL == atype ) ) {
            throw new GLException("FBO depth buffer already attached (rb "+depth+"), type is "+atype+", "+toHexString(internalFormat)+", "+this);
        }
        if( null != stencil && ( Attachment.Type.STENCIL== atype || Attachment.Type.DEPTH_STENCIL == atype ) ) {
            throw new GLException("FBO stencil buffer already attached (rb "+stencil+"), type is "+atype+", "+toHexString(internalFormat)+", "+this);
        }
        bind(gl);

        attachRenderbufferImpl2(gl, atype, internalFormat);
    }

    private final void attachRenderbufferImpl2(final GL gl, final Attachment.Type atype, final int internalFormat) throws GLException {
        // atype and current depth and stencil instance are already validated in 'attachRenderbufferImpl(..)'
        if( Attachment.Type.DEPTH == atype ) {
            if(null == depth) {
                depth = createRenderAttachment(Type.DEPTH, internalFormat, samples, width, height);
            } else {
                depth.setSize(width, height);
                depth.setSamples(samples);
            }
            validateAttachmentSize(depth);
            depth.initialize(gl);
        } else if( Attachment.Type.STENCIL == atype ) {
            if(null == stencil) {
                stencil = createRenderAttachment(Type.STENCIL, internalFormat, samples, width, height);
            } else {
                stencil.setSize(width, height);
                stencil.setSamples(samples);
            }
            validateAttachmentSize(stencil);
            stencil.initialize(gl);
        } else if( Attachment.Type.DEPTH_STENCIL == atype ) {
            if(null == depth) {
                if(null != stencil) {
                    throw new InternalError("XXX: DEPTH_STENCIL, depth was null, stencil not: "+this.toString());
                }
                depth = createRenderAttachment(Type.DEPTH_STENCIL, internalFormat, samples, width, height);
            } else {
                depth.setSize(width, height);
                depth.setSamples(samples);
            }
            validateAttachmentSize(depth);
            depth.initialize(gl);
            // DEPTH_STENCIL shares buffer w/ depth and stencil
            stencil = depth;
        }

        // Attach the buffer
        if( Attachment.Type.DEPTH == atype ) {
            gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_DEPTH_ATTACHMENT, GL.GL_RENDERBUFFER, depth.getName());
        } else if( Attachment.Type.STENCIL == atype ) {
            gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_STENCIL_ATTACHMENT, GL.GL_RENDERBUFFER, stencil.getName());
        } else if( Attachment.Type.DEPTH_STENCIL == atype ) {
            gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_DEPTH_ATTACHMENT, GL.GL_RENDERBUFFER, depth.getName());
            gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_STENCIL_ATTACHMENT, GL.GL_RENDERBUFFER, stencil.getName());
        }

        modified = true;

        if(!ignoreStatus) {
            updateStatus(gl);
            if( !isStatusValid() ) {
                detachRenderbuffer(gl, atype, true);
                throw new GLException("renderbuffer [attachmentType "+atype+", iformat "+toHexString(internalFormat)+"] failed: "+this.getStatusString()+": "+this.toString());
            }
        }

        if(DEBUG) {
            System.err.println("FBObject.attachRenderbuffer.X: [attachmentType "+atype+", iformat "+toHexString(internalFormat)+"]: "+this);
        }
    }

    /**
     * Detaches a {@link Colorbuffer}, i.e. {@link ColorAttachment} or {@link TextureAttachment}.
     * <p>Leaves the FBO bound!</p>
     *
     * @param gl
     * @param attachmentPoint
     * @param dispose true if the Colorbuffer shall be disposed
     * @return the detached Colorbuffer
     * @throws IllegalArgumentException
     */
    public final Colorbuffer detachColorbuffer(final GL gl, final int attachmentPoint, final boolean dispose) throws IllegalArgumentException {
        bind(gl);

        final Colorbuffer res = detachColorbufferImpl(gl, attachmentPoint, dispose ? DetachAction.DISPOSE : DetachAction.NONE, 0);
        if(null == res) {
            throw new IllegalArgumentException("ColorAttachment at "+attachmentPoint+", not attached, "+this);
        }
        if(DEBUG) {
            System.err.println("FBObject.detachColorbuffer.X: [attachmentPoint "+attachmentPoint+", dispose "+dispose+"]: "+res+", "+this);
        }
        return res;
    }

    private final Colorbuffer detachColorbufferImpl(final GL gl, final int attachmentPoint, final DetachAction detachAction, final int sampleCountChange) {
        final Colorbuffer colbufOld = colorbufferAttachments[attachmentPoint]; // shortcut, don't validate here

        if(null == colbufOld) {
            return null;
        }

        removeColorAttachment(attachmentPoint, colbufOld);

        if( colbufOld.isTextureAttachment() ) {
            final TextureAttachment texA = colbufOld.getTextureAttachment();
            if( 0 != texA.getName() ) {
                gl.glFramebufferTexture2D(GL.GL_FRAMEBUFFER,
                              GL.GL_COLOR_ATTACHMENT0 + attachmentPoint,
                              GL.GL_TEXTURE_2D, 0, 0);
                gl.glBindTexture(GL.GL_TEXTURE_2D, 0);
                switch(detachAction) {
                    case DISPOSE:
                    case RECREATE:
                        texA.free(gl);
                        break;
                    default:
                }
            }
            if(DetachAction.RECREATE == detachAction) {
                final Colorbuffer colbufNew;
                if( 0 < sampleCountChange ) {
                    // switch to MSAA: TextureAttachment -> ColorAttachment
                    colbufNew = createColorAttachment(hasAlpha(texA.format));
                } else {
                    // keep MSAA settings
                    texA.setSize(width, height);
                    colbufNew = texA;
                }
                attachColorbufferImpl(gl, attachmentPoint, colbufNew);
            }
        } else {
            final ColorAttachment colA = colbufOld.getColorAttachment();
            if( 0 != colA.getName() ) {
                gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER,
                                             GL.GL_COLOR_ATTACHMENT0+attachmentPoint,
                                             GL.GL_RENDERBUFFER, 0);
                switch(detachAction) {
                    case DISPOSE:
                    case RECREATE:
                        colA.free(gl);
                        break;
                    default:
                }
            }
            if(DetachAction.RECREATE == detachAction) {
                final Colorbuffer colbufNew;
                if( 0 <= sampleCountChange || null == samplingColorSink ) {
                    // keep ColorAttachment,
                    // including 'switch to non-MSAA' if no samplingColorSink is available
                    // to determine whether a TextureAttachment or ColorAttachment is desired!
                    colA.setSize(width, height);
                    colA.setSamples(samples);
                    colbufNew = colA;
                } else {
                    // switch to non MSAA
                    if( samplingColorSink.isTextureAttachment() ) {
                        final TextureAttachment samplingTextureSink = samplingColorSink.getTextureAttachment();
                        colbufNew = createColorTextureAttachment(samplingTextureSink.format, width, height,
                                                                 samplingTextureSink.dataFormat, samplingTextureSink.dataType,
                                                                 samplingTextureSink.magFilter, samplingTextureSink.minFilter,
                                                                 samplingTextureSink.wrapS, samplingTextureSink.wrapT);
                    } else {
                        colbufNew = createColorAttachment(samplingColorSink.getFormat(), 0, width, height);
                    }
                }
                attachColorbuffer(gl, attachmentPoint, colbufNew);
            }
        }
        return colbufOld;
    }

    private final void freeAllColorbufferImpl(final GL gl) {
        for(int i=0; i<maxColorAttachments; i++) {
            final Colorbuffer colbuf = colorbufferAttachments[i]; // shortcut, don't validate here

            if(null == colbuf) {
                return;
            }

            if( colbuf.isTextureAttachment() ) {
                final TextureAttachment texA = colbuf.getTextureAttachment();
                if( 0 != texA.getName() ) {
                    gl.glFramebufferTexture2D(GL.GL_FRAMEBUFFER,
                                  GL.GL_COLOR_ATTACHMENT0 + i,
                                  GL.GL_TEXTURE_2D, 0, 0);
                    gl.glBindTexture(GL.GL_TEXTURE_2D, 0);
                }
                texA.free(gl);
            } else {
                final ColorAttachment colA = colbuf.getColorAttachment();
                if( 0 != colA.getName() ) {
                    gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER,
                                                 GL.GL_COLOR_ATTACHMENT0 + i,
                                                 GL.GL_RENDERBUFFER, 0);
                }
                colA.free(gl);
            }
        }
    }

    /**
     *
     * @param gl
     * @param dispose true if the Colorbuffer shall be disposed
     * @param reqAType {@link Type#DEPTH}, {@link Type#DEPTH} or {@link Type#DEPTH_STENCIL}
     */
    public final void detachRenderbuffer(final GL gl, final Attachment.Type atype, final boolean dispose) throws IllegalArgumentException {
        bind(gl);
        final RenderAttachment res = detachRenderbufferImpl(gl, atype, dispose ? DetachAction.DISPOSE : DetachAction.NONE);
        if(null == res) {
            throw new IllegalArgumentException("RenderAttachment type "+atype+", not attached, "+this);
        }
        if(DEBUG) {
            System.err.println("FBObject.detachRenderbuffer.X: [attachmentType "+atype+", dispose "+dispose+"]: "+this);
        }
    }

    public final boolean isDepthStencilPackedFormat() {
        final boolean res = null != depth && null != stencil &&
                            depth.format == stencil.format ;
        if(res) {
            if(depth.getName() != stencil.getName() ) {
                throw new InternalError("depth/stencil packed format not sharing: depth "+depth+", stencil "+stencil);
            }
            if(depth != stencil) {
                throw new InternalError("depth/stencil packed format not a shared reference: depth "+depth+", stencil "+stencil);
            }
        }
        return res;
    }

    private final RenderAttachment detachRenderbufferImpl(final GL gl, Attachment.Type atype, final DetachAction detachAction) throws IllegalArgumentException {
        switch ( atype ) {
            case DEPTH:
            case STENCIL:
            case DEPTH_STENCIL:
             break;
             default:
                 throw new IllegalArgumentException("only depth/stencil types allowed, was "+atype+", "+this);
        }
        if( null == depth && null == stencil ) {
            return null; // nop
        }
        final boolean packed = isDepthStencilPackedFormat();
        if( packed ) {
            // Note: DEPTH_STENCIL shares buffer w/ depth and stencil
            atype = Attachment.Type.DEPTH_STENCIL;
        }
        final RenderAttachment renderOld;
        switch ( atype ) {
            case DEPTH:
                renderOld = depth;
                if( null != renderOld ) {
                    final int format = renderOld.format;
                    if( 0 != renderOld.getName() ) {
                        gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_DEPTH_ATTACHMENT, GL.GL_RENDERBUFFER, 0);
                        switch(detachAction) {
                            case DISPOSE:
                            case RECREATE:
                                renderOld.free(gl);
                                break;
                            default:
                        }
                    }
                    if(DetachAction.RECREATE == detachAction) {
                        attachRenderbufferImpl2(gl, atype, format);
                    } else {
                        depth = null;
                    }
                }
                break;
            case STENCIL:
                renderOld = stencil;
                if( null != renderOld ) {
                    final int format = renderOld.format;
                    if(0 != renderOld.getName()) {
                        gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_STENCIL_ATTACHMENT, GL.GL_RENDERBUFFER, 0);
                        switch(detachAction) {
                            case DISPOSE:
                            case RECREATE:
                                renderOld.free(gl);
                                break;
                            default:
                        }
                    }
                    if(DetachAction.RECREATE == detachAction) {
                        attachRenderbufferImpl2(gl, atype, format);
                    } else {
                        stencil = null;
                    }
                }
                break;
            case DEPTH_STENCIL:
                renderOld = depth;
                if( null != renderOld ) {
                    final int format = renderOld.format;
                    if(0 != renderOld.getName()) {
                        gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_DEPTH_ATTACHMENT, GL.GL_RENDERBUFFER, 0);
                        if(packed) {
                            gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_STENCIL_ATTACHMENT, GL.GL_RENDERBUFFER, 0);
                        }
                        switch(detachAction) {
                            case DISPOSE:
                            case RECREATE:
                                renderOld.free(gl);
                                break;
                            default:
                        }
                    }
                    if(DetachAction.RECREATE == detachAction) {
                        attachRenderbufferImpl2(gl, packed ? Attachment.Type.DEPTH_STENCIL : Attachment.Type.DEPTH, format);
                    } else {
                        depth = null;
                        if(packed) {
                            stencil = null;
                        }
                    }
                }
                if( !packed && null != stencil ) {
                    final int format = stencil.format;
                    if(0 != stencil.getName()) {
                        gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_STENCIL_ATTACHMENT, GL.GL_RENDERBUFFER, 0);
                        switch(detachAction) {
                            case DISPOSE:
                            case RECREATE:
                                stencil.free(gl);
                                break;
                            default:
                        }
                    }
                    if(DetachAction.RECREATE == detachAction) {
                        attachRenderbufferImpl2(gl, Attachment.Type.STENCIL, format);
                    } else {
                        stencil = null;
                    }
                }
                break;
             default:
                 throw new InternalError("XXX"); // handled by caller
        }
        modified = true;
        return renderOld;
    }

    private final void freeAllRenderbufferImpl(final GL gl) throws IllegalArgumentException {
        // Note: DEPTH_STENCIL shares buffer w/ depth and stencil
        final boolean packed = isDepthStencilPackedFormat();
        if( null != depth ) {
            if(0 != depth.getName()) {
                gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_DEPTH_ATTACHMENT, GL.GL_RENDERBUFFER, 0);
                if(packed) {
                    gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_STENCIL_ATTACHMENT, GL.GL_RENDERBUFFER, 0);
                }
                depth.free(gl);
            }
        }
        if( !packed && null != stencil ) {
            if(0 != stencil.getName()) {
                gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_STENCIL_ATTACHMENT, GL.GL_RENDERBUFFER, 0);
                stencil.free(gl);
            }
        }
    }

    /**
     * Detaches all {@link ColorAttachment}s, {@link TextureAttachment}s and {@link RenderAttachment}s
     * and disposes them.
     * <p>Leaves the FBO bound, if initialized!</p>
     * <p>
     * An attached sampling sink texture will be detached as well, see {@link #getSamplingTextureSink()}.
     * </p>
     * @param gl the current GL context
     */
    public final void detachAll(final GL gl) {
        if(null != samplingSink) {
            samplingSink.detachAll(gl);
        }
        detachAllImpl(gl, true/* detachNonColorbuffer */, false /* recreate */, 0);
    }

    /**
     * Detaches all {@link ColorAttachment}s and {@link TextureAttachment}s
     * and disposes them.
     * <p>Leaves the FBO bound, if initialized!</p>
     * <p>
     * An attached sampling sink texture will be detached as well, see {@link #getSamplingTextureSink()}.
     * </p>
     * @param gl the current GL context
     */
    public final void detachAllColorbuffer(final GL gl) {
        if(null != samplingSink) {
            samplingSink.detachAllColorbuffer(gl);
        }
        detachAllImpl(gl, false/* detachNonColorbuffer */, false /* recreate */, 0);
    }

    /**
     * Detaches all {@link TextureAttachment}s and disposes them.
     * <p>Leaves the FBO bound, if initialized!</p>
     * <p>
     * An attached sampling sink texture will be detached as well, see {@link #getSamplingTextureSink()}.
     * </p>
     * @param gl the current GL context
     */
    public final void detachAllTexturebuffer(final GL gl) {
        if( !isInitialized() ) {
            return;
        }
        if(null != samplingSink) {
            samplingSink.detachAllTexturebuffer(gl);
        }
        bind(gl);
        for(int i=0; i<maxColorAttachments; i++) {
            if( colorbufferAttachments[i].isTextureAttachment() ) {
                detachColorbufferImpl(gl, i, DetachAction.DISPOSE, 0);
            }
        }
        if(DEBUG) {
            System.err.println("FBObject.detachAllTexturebuffer.X: "+this);
        }
    }

    public final void detachAllRenderbuffer(final GL gl) {
        if( !isInitialized() ) {
            return;
        }
        if(null != samplingSink) {
            samplingSink.detachAllRenderbuffer(gl);
        }
        bind(gl);
        detachRenderbufferImpl(gl, Attachment.Type.DEPTH_STENCIL, DetachAction.DISPOSE);
    }

    private final void detachAllImpl(final GL gl, final boolean detachNonColorbuffer, final boolean recreate, final int sampleCountChange) {
        if( !isInitialized() ) {
            return;
        }
        ignoreStatus = recreate; // ignore status on single calls only if recreate -> reset
        try {
            bind(gl);
            if(FBOResizeQuirk) {
                if(detachNonColorbuffer && recreate) {
                    // free all colorbuffer & renderbuffer 1st
                    freeAllColorbufferImpl(gl);
                    freeAllRenderbufferImpl(gl);
                }
            }
            for(int i=0; i<maxColorAttachments; i++) {
                detachColorbufferImpl(gl, i, recreate ? DetachAction.RECREATE : DetachAction.DISPOSE, sampleCountChange);
            }
            if( !recreate && colorbufferCount>0 ) {
                throw new InternalError("Non zero ColorAttachments "+this);
            }

            if(detachNonColorbuffer) {
                detachRenderbufferImpl(gl, Attachment.Type.DEPTH_STENCIL, recreate ? DetachAction.RECREATE : DetachAction.DISPOSE);
            }
            if(ignoreStatus) { // post validate
                /* if(true) {
                    throw new GLException("Simulating bug 617, reset FBO failure");
                } */
                updateStatus(gl);
                if(!isStatusValid()) {
                    throw new GLException("detachAllImpl failed "+getStatusString()+", "+this);
                }
            }
        } finally {
            ignoreStatus = false;
        }
        if(DEBUG) {
            System.err.println("FBObject.detachAll.X: [resetNonColorbuffer "+detachNonColorbuffer+", recreate "+recreate+"]: "+this);
        }
    }

    /**
     * @param gl the current GL context
     */
    public final void destroy(final GL gl) {
        if(!initialized) {
            return;
        }
        if(DEBUG) {
            System.err.println("FBObject.destroy.0: "+this);
            // Thread.dumpStack();
        }
        if( null != samplingSink && samplingSink.isInitialized() ) {
            samplingSink.destroy(gl);
        }

        detachAllImpl(gl, true /* detachNonColorbuffer */, false /* recreate */, 0);

        // cache FB names, preset exposed to zero,
        // braking ties w/ GL/GLContext link to getReadFramebuffer()/getWriteFramebuffer()
        final int fb_cache = fbName;
        fbName = 0;

        final int name[] = new int[1];
        if(0!=fb_cache) {
            name[0] = fb_cache;
            gl.glDeleteFramebuffers(1, name, 0);
        }
        initialized = false;
        bound = false;
        if(DEBUG) {
            System.err.println("FBObject.destroy.X: "+this);
        }
    }

    private final boolean sampleSinkSizeMismatch() {
        return samplingSink.getWidth() != width || samplingSink.getHeight() != height ;
    }
    private final boolean sampleSinkDepthStencilMismatch() {
        if ( ( null != depth && ( null == samplingSink.depth || depth.format != samplingSink.depth.format ) )
             ||
             ( null == depth && null != samplingSink.depth )
           ) {
            return true;
        }

        if ( ( null != stencil && ( null == samplingSink.stencil || stencil.format != samplingSink.stencil.format ) )
             ||
             ( null == stencil && null != samplingSink.stencil )
           ) {
            return true;
        }

        return false;
    }
    /**
     * For GLES3, sampling-sink {@link Colorbuffer} <i>internal format</i> <b>must be equal</b> w/ the sampling-source {@link Colorbuffer}.
     * Implementation aligns w/ {@link #createColorTextureAttachment(GLProfile, boolean, int, int, int, int, int, int)}
     * and {@link #createColorAttachment(boolean)}.
     */
    private final boolean sampleSinkExFormatMismatch(final GL gl) {
        if( null != samplingColorSink && getColorbufferCount() > 0 && gl.isGL2ES3() ) {
            final Attachment ca = (Attachment)getColorbuffer(0); // should be at attachment-point 0
            // We cannot comply w/ attachment's format other than attachment point 0!
            // return ( null != ca && ca.format != samplingColorSink.getFormat() ) ||
            //        hasAlpha(samplingColorSink.getFormat()) != hasAttachmentUsingAlpha();
            return null != ca && ca.format != samplingColorSink.getFormat();
        }
        return false;
    }

    /**
     * Manually validates the MSAA sampling sink, if used.
     * <p>
     * If MSAA is being used and no sampling sink is attached via {@link #setSamplingSink(FBObject)}
     * a new sampling sink is being created.
     * </p>
     * <p>
     * If the sampling sink size or attributes differs from the source, its attachments are reset
     * to match the source.
     * </p>
     * <p>
     * Automatically called by {@link #reset(GL, int, int, int, boolean)}
     * and {@link #syncSamplingSink(GL)}.
     * </p>
     * <p>
     * It is recommended to call this method after initializing the FBO and attaching renderbuffer etc for the 1st time
     * if access to sampling sink resources is required.
     * </p>
     *
     * <p>Leaves the FBO bound state untouched</p>
     *
     * @param gl the current GL context
     * @return {@code true} if this instance has been modified, otherwise {@code false}.
     * @throws GLException in case of an error, i.e. size too big, etc ..
     */
    public final boolean resetSamplingSink(final GL gl) throws GLException {
        if(DEBUG) {
            System.err.println("FBObject.resetSamplingSink.0");
            Thread.dumpStack();
        }

        if( 0 == samples ) {
            final boolean modifiedInstance;
            // MSAA off
            if( null != samplingSink ) {
                // cleanup
                if( samplingSink.initialized ) {
                    samplingSink.detachAll(gl);
                }
                samplingSink = null;
                samplingColorSink = null;
                modifiedInstance = true;
            } else {
                modifiedInstance = false;
            }
            this.modified = false;
            if(DEBUG) {
                System.err.println("FBObject.resetSamplingSink.X1: zero samples, mod "+modifiedInstance+"\n\tTHIS "+this);
            }
            return modifiedInstance;
        }

        boolean modifiedInstance = false;

        if( null == samplingSink ) {
            samplingSink = new FBObject();
            samplingSink.init(gl, width, height, 0);
            samplingColorSink = null;
            modifiedInstance = true;
        } else if( !samplingSink.initialized ) {
            throw new InternalError("InitState Mismatch: samplingSink set, but not initialized "+samplingSink);
        } else if( null == samplingColorSink || 0 == samplingColorSink.getName() ) {
            throw new InternalError("InitState Mismatch: samplingColorSink set, but not initialized "+samplingColorSink+", "+samplingSink);
        }

        if(DEBUG) {
            System.err.println("FBObject.resetSamplingSink.1: mod "+modifiedInstance+"\n\tTHIS "+this+",\n\tSINK "+samplingSink);
        }
        boolean sampleSinkExFormatMismatch = sampleSinkExFormatMismatch(gl);
        boolean sampleSinkSizeMismatch = sampleSinkSizeMismatch();
        boolean sampleSinkDepthStencilMismatch = sampleSinkDepthStencilMismatch();

        if( modifiedInstance ) {
            // samplingColorSink == null
            // must match size, format and colorbuffer do not exist yet
            if( sampleSinkExFormatMismatch || sampleSinkSizeMismatch ) {
                throw new InternalError("InitState Mismatch: Matching exFormat "+!sampleSinkExFormatMismatch+
                                   ", size "+!sampleSinkSizeMismatch +", "+this);
            }
        } else {
            // samplingColorSink != null
            if(!sampleSinkExFormatMismatch && !sampleSinkSizeMismatch && !sampleSinkDepthStencilMismatch) {
                if(DEBUG) {
                    System.err.println("FBObject.resetSamplingSink.X2: Matching: exFormat "+!sampleSinkExFormatMismatch+
                                       ", size "+!sampleSinkSizeMismatch +", depthStencil "+!sampleSinkDepthStencilMismatch+
                                       ", mod "+modifiedInstance);
                }
                // all properties match ..
                samplingSink.modified = false;
                this.modified = false;
                return modifiedInstance;
            }
        }

        final boolean wasBound;
        if( isBound() ) {
            markUnbound(); // automatic GL unbind by sampleSink binding
            wasBound = true;
        } else {
            wasBound = false;
        }

        if(DEBUG) {
            System.err.println("FBObject.resetSamplingSink.2: wasBound "+wasBound+", matching: exFormat "+!sampleSinkExFormatMismatch+
                               ", size "+!sampleSinkSizeMismatch +", depthStencil "+!sampleSinkDepthStencilMismatch);
        }

        modifiedInstance = true;

        if( sampleSinkDepthStencilMismatch ) { // includes 1st init
            samplingSink.detachAllRenderbuffer(gl);
        }

        final boolean samplingColorSinkShallBeTA = null == samplingColorSink || samplingColorSink.isTextureAttachment();

        if( sampleSinkExFormatMismatch ) {
            samplingSink.detachAllColorbuffer(gl);
            samplingColorSink = null;
        } else if( sampleSinkSizeMismatch ) {
            samplingSink.resetSizeImpl(gl, width, height);
            samplingColorSink = samplingSink.getColorbuffer(0);
        }

        if( null == samplingColorSink ) { // sampleSinkFormatMismatch || 1st init
            final Colorbuffer cb0 = getColorbuffer(0); // align with colorbuffer at attachment-point 0
            if( null != cb0 ) {
                // match pre-existing format
                if( samplingColorSinkShallBeTA ) {
                    samplingColorSink = createColorTextureAttachment(gl, cb0.getFormat(), width, height,
                                                                     GL.GL_NEAREST, GL.GL_NEAREST,
                                                                     GL.GL_CLAMP_TO_EDGE, GL.GL_CLAMP_TO_EDGE);
                } else {
                    samplingColorSink = createColorAttachment(cb0.getFormat(), 0, width, height);
                }
                samplingSink.attachColorbuffer(gl, 0, samplingColorSink);
            } else {
                // match default format
                final boolean hasAlpha = hasAttachmentUsingAlpha();
                if( samplingColorSinkShallBeTA ) {
                    samplingColorSink = samplingSink.attachTexture2D(gl, 0, hasAlpha);
                } else {
                    samplingColorSink = samplingSink.attachColorbuffer(gl, 0, hasAlpha);
                }
            }
        }

        if( sampleSinkDepthStencilMismatch ) { // includes 1st init
            samplingSink.attachRenderbuffer(gl, depth.format);
            if( null != stencil && !isDepthStencilPackedFormat() ) {
                samplingSink.attachRenderbuffer(gl, stencil.format);
            }
        }

        sampleSinkExFormatMismatch = sampleSinkExFormatMismatch(gl);
        sampleSinkSizeMismatch = sampleSinkSizeMismatch();
        sampleSinkDepthStencilMismatch = sampleSinkDepthStencilMismatch();
        if(sampleSinkExFormatMismatch || sampleSinkSizeMismatch || sampleSinkDepthStencilMismatch) {
            throw new InternalError("Samples sink mismatch after reset: \n\tTHIS "+this+",\n\t SINK "+samplingSink+
                                    "\n\t Mismatch. Matching: exFormat "+!sampleSinkExFormatMismatch+
                                    ", size "+!sampleSinkSizeMismatch +", depthStencil "+!sampleSinkDepthStencilMismatch);
        }

        samplingSink.modified = false;
        samplingSink.unbind(gl);
        this.modified = false;

        if(wasBound) {
            bind(gl);
        }

        if(DEBUG) {
            System.err.println("FBObject.resetSamplingSink.XX: END mod "+modifiedInstance+"\n\tTHIS "+this+",\n\tSINK "+samplingSink+
                               "\n\t Matching: exFormat "+!sampleSinkExFormatMismatch+
                               ", size "+!sampleSinkSizeMismatch +", depthStencil "+!sampleSinkDepthStencilMismatch);
        }
        return modifiedInstance;
    }

    /**
     * Setting this FBO sampling sink.
     * @param newSamplingSink the new and initialized FBO sampling sink to use, or null to remove current sampling sink
     * @return the previous sampling sink or null if none was attached
     * @throws GLException if this FBO doesn't use MSAA or the given sink uses MSAA itself
     * @throws IllegalStateException if the {@code newSamplingSink} is not null and not initialized
     */
    public FBObject setSamplingSink(final FBObject newSamplingSink) throws /* IllegalStateException, */ GLException {
        final FBObject prev = samplingSink;
        if( null == newSamplingSink) {
            samplingSink = null;
            samplingColorSink = null;
        } else if( samples > 0 ) {
            if( !newSamplingSink.isInitialized() ) {
                throw new IllegalStateException("SamplingSink not initialized: "+newSamplingSink);
            }
            if( newSamplingSink.getNumSamples() > 0 ) {
                throw new GLException("SamplingSink FBO cannot use MSAA itself: "+newSamplingSink);
            }
            samplingSink = newSamplingSink;
            samplingColorSink = newSamplingSink.getColorbuffer(0);
        } else {
            throw new GLException("Setting SamplingSink for non MSAA FBO not allowed: "+this);
        }
        modified = true;
        samplingSinkDirty = true;
        return prev;
    }

    /**
     * Bind this FBO, i.e. bind write framebuffer to {@link #getWriteFramebuffer()}.
     *
     * <p>
     * If multisampling is used, it sets the read framebuffer to the sampling sink {@link #getWriteFramebuffer()}.
     * </p>
     * <p>
     * In case you have attached more than one color buffer,
     * you may want to setup {@link GL2ES3#glDrawBuffers(int, int[], int)}.
     * </p>
     * @param gl the current GL context
     * @throws GLException
     */
    public final void bind(final GL gl) throws GLException {
        if(!bound || fbName != gl.getBoundFramebuffer(GL.GL_FRAMEBUFFER)) {
            checkInitialized();
            if( fullFBOSupport ) {
                gl.glBindFramebuffer(GL2ES3.GL_DRAW_FRAMEBUFFER, getWriteFramebuffer()); // this fb, msaa or normal
                gl.glBindFramebuffer(GL2ES3.GL_READ_FRAMEBUFFER, getReadFramebuffer());  // msaa: sampling sink, normal: this fb
            } else {
                gl.glBindFramebuffer(GL.GL_FRAMEBUFFER, getWriteFramebuffer()); // normal: read/write
            }
            bound = true;
            samplingSinkDirty = true;
        }
    }

    /**
     * Unbind this FBO, i.e. bind read and write framebuffer to default, see {@link GLBase#getDefaultDrawFramebuffer()}.
     *
     * <p>If full FBO is supported, sets the read and write framebuffer individually to default, hence not disturbing
     * an optional operating MSAA FBO, see {@link GLBase#getDefaultReadFramebuffer()} and {@link GLBase#getDefaultDrawFramebuffer()}</p>
     *
     * @param gl the current GL context
     * @throws GLException
     */
    public final void unbind(final GL gl) throws GLException {
        if(bound) {
            if(fullFBOSupport) {
                // default read/draw buffers, may utilize GLContext/GLDrawable override of
                // GLContext.getDefaultDrawFramebuffer() and GLContext.getDefaultReadFramebuffer()
                gl.glBindFramebuffer(GL2ES3.GL_DRAW_FRAMEBUFFER, 0);
                gl.glBindFramebuffer(GL2ES3.GL_READ_FRAMEBUFFER, 0);
            } else {
                gl.glBindFramebuffer(GL.GL_FRAMEBUFFER, 0); // default draw buffer
            }
            bound = false;
        }
    }

    /**
     * Method simply marks this FBO unbound w/o interfering w/ the bound framebuffer as perfomed by {@link #unbind(GL)}.
     * <p>
     * Only use this method if a subsequent {@link #unbind(GL)}, {@link #use(GL, TextureAttachment)} or {@link #bind(GL)}
     * follows on <i>any</i> FBO.
     * </p>
     */
    public final void markUnbound() {
        bound = false;
    }

    /**
     * Returns <code>true</code> if framebuffer object is bound via {@link #bind(GL)}, otherwise <code>false</code>.
     * <p>
     * Method verifies the bound state via {@link GL#getBoundFramebuffer(int)}.
     * </p>
     * @param gl the current GL context
     */
    public final boolean isBound(final GL gl) {
        bound = bound && fbName == gl.getBoundFramebuffer(GL.GL_FRAMEBUFFER) ;
        return bound;
    }

    /** Returns <code>true</code> if framebuffer object is bound via {@link #bind(GL)}, otherwise <code>false</code>. */
    public final boolean isBound() { return bound; }

    /**
     * If multisampling is being used and flagged dirty by a previous call of {@link #bind(GL)} or after initialization,
     * the msaa-buffers are sampled to it's sink {@link #getSamplingTextureSink()}.
     * <p>
     * Method also resets the sampling sink configuration via {@link #resetSamplingSink(GL)} if used and required.
     * </p>
     * <p>
     * Method is called automatically by {@link #use(GL, TextureAttachment)}.
     * </p>
     * <p>
     * Method always resets the framebuffer binding to default in the end.
     * If full FBO is supported, sets the read and write framebuffer individually to default after sampling, hence not disturbing
     * an optional operating MSAA FBO, see {@link GLBase#getDefaultReadFramebuffer()} and {@link GLBase#getDefaultDrawFramebuffer()}
     * </p>
     * <p>
     * In case you use this FBO w/o the {@link GLFBODrawable} and intend to employ {@link GL#glReadPixels(int, int, int, int, int, int, java.nio.Buffer) glReadPixels(..)}
     * you may want to call {@link GL#glBindFramebuffer(int, int) glBindFramebuffer}({@link GL2ES3#GL_READ_FRAMEBUFFER}, {@link #getReadFramebuffer()});
     * </p>
     * <p>Leaves the FBO unbound.</p>
     *
     * @param gl the current GL context
     * @param ta {@link TextureAttachment} to use, prev. attached w/  {@link #attachTexture2D(GL, int, boolean, int, int, int, int) attachTexture2D(..)}
     * @throws IllegalArgumentException
     */
    public final void syncSamplingSink(final GL gl) {
        markUnbound();
        if(samples>0 && samplingSinkDirty) { // implies fullFBOSupport
            samplingSinkDirty = false;
            if( isModified() ) {
                resetSamplingSink(gl);
            }
            checkPreGLError(gl);
            gl.glBindFramebuffer(GL2ES3.GL_READ_FRAMEBUFFER, fbName); // read from this MSAA fb
            gl.glBindFramebuffer(GL2ES3.GL_DRAW_FRAMEBUFFER, samplingSink.getWriteFramebuffer()); // write to sampling sink
            ((GL2ES3)gl).glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, // since MSAA is supported, casting to GL2ES3 is OK
                                           GL.GL_COLOR_BUFFER_BIT, GL.GL_NEAREST);
            checkNoError(null, gl.glGetError(), "FBObject syncSampleSink"); // throws GLException if error
        } else {
            modified = false;
        }
        if(fullFBOSupport) {
            // default read/draw buffers, may utilize GLContext/GLDrawable override of
            // GLContext.getDefaultDrawFramebuffer() and GLContext.getDefaultReadFramebuffer()
            gl.glBindFramebuffer(GL2ES3.GL_DRAW_FRAMEBUFFER, 0);
            gl.glBindFramebuffer(GL2ES3.GL_READ_FRAMEBUFFER, 0);
        } else {
            gl.glBindFramebuffer(GL.GL_FRAMEBUFFER, 0); // default draw buffer
        }
    }

    /**
     * {@link #syncSamplingSink(GL) Synchronize the sampling sink} and bind the given {@link TextureAttachment}, if not <code>null</code>.
     *
     * <p>If using a {@link TextureAttachment} and multiple texture units, ensure you call {@link GL#glActiveTexture(int)} first!</p>
     *
     * <p>{@link #syncSamplingSink(GL)} is being called</p>
     *
     * <p>Leaves the FBO unbound!</p>
     *
     * @param gl the current GL context
     * @param ta {@link TextureAttachment} to use, prev. attached w/  {@link #attachTexture2D(GL, int, boolean, int, int, int, int) attachTexture2D(..)},
     *           may be <code>null</code> in case no {@link TextureAttachment} is used.
     * @throws IllegalArgumentException
     */
    public final void use(final GL gl, final TextureAttachment ta) throws IllegalArgumentException {
        syncSamplingSink(gl);
        if( null != ta ) {
            gl.glBindTexture(GL.GL_TEXTURE_2D, ta.getName()); // use it ..
        }
    }

    /**
     * Unbind texture, ie bind 'non' texture 0
     *
     * <p>Leaves the FBO unbound.</p>
     */
    public final void unuse(final GL gl) {
        unbind(gl);
        gl.glBindTexture(GL.GL_TEXTURE_2D, 0); // don't use it
    }

    /** @see GL#hasFullFBOSupport() */
    public final boolean hasFullFBOSupport() throws GLException { checkInitialized(); return this.fullFBOSupport; }

    /**
     * Returns <code>true</code> if renderbuffer accepts internal format {@link GL#GL_RGB8} and {@link GL#GL_RGBA8}, otherwise <code>false</code>.
     * @throws GLException if {@link #init(GL)} hasn't been called.
     */
    public final boolean supportsRGBA8() throws GLException { checkInitialized(); return rgba8Avail; }

    /**
     * Returns <code>true</code> if {@link GL#GL_DEPTH_COMPONENT16}, {@link GL#GL_DEPTH_COMPONENT24} or {@link GL#GL_DEPTH_COMPONENT32} is supported, otherwise <code>false</code>.
     * @param bits 16, 24 or 32 bits
     * @throws GLException if {@link #init(GL)} hasn't been called.
     */
    public final boolean supportsDepth(final int bits) throws GLException {
        checkInitialized();
        switch(bits) {
            case 16: return true;
            case 24: return depth24Avail;
            case 32: return depth32Avail;
            default: return false;
        }
    }

    /**
     * Returns <code>true</code> if {@link GL#GL_STENCIL_INDEX1}, {@link GL#GL_STENCIL_INDEX4}, {@link GL#GL_STENCIL_INDEX8} or {@link GL2GL3#GL_STENCIL_INDEX16} is supported, otherwise <code>false</code>.
     * @param bits 1, 4, 8 or 16 bits
     * @throws GLException if {@link #init(GL)} hasn't been called.
     */
    public final boolean supportsStencil(final int bits) throws GLException {
        checkInitialized();
        switch(bits) {
            case  1: return stencil01Avail;
            case  4: return stencil04Avail;
            case  8: return stencil08Avail;
            case 16: return stencil16Avail;
            default: return false;
        }
    }

    /**
     * Returns <code>true</code> if {@link GL#GL_DEPTH24_STENCIL8} is supported, otherwise <code>false</code>.
     * @throws GLException if {@link #init(GL)} hasn't been called.
     */
    public final boolean supportsPackedDepthStencil() throws GLException { checkInitialized(); return packedDepthStencilAvail; }

    /**
     * Returns the maximum number of colorbuffer attachments.
     * @throws GLException if {@link #init(GL)} hasn't been called.
     */
    public final int getMaxColorAttachments() throws GLException { checkInitialized(); return maxColorAttachments; }

    public final int getMaxTextureSize() throws GLException { checkInitialized(); return this.maxTextureSize; }
    public final int getMaxRenderbufferSize() throws GLException { checkInitialized(); return this.maxRenderbufferSize; }

    /** @see GL#getMaxRenderbufferSamples() */
    public final int getMaxSamples() throws GLException { checkInitialized(); return this.maxSamples; }

    /**
     * Returns <code>true</code> if this instance has been initialized with {@link #reset(GL, int, int)}
     * or {@link #reset(GL, int, int, int, boolean)}, otherwise <code>false</code>
     */
    public final boolean isInitialized() { return initialized; }
    /** Returns the width */
    public final int getWidth() { return width; }
    /** Returns the height */
    public final int getHeight() { return height; }
    /** Returns the number of samples for multisampling (MSAA). zero if no multisampling is used. */
    public final int getNumSamples() { return samples; }
    /** Returns the framebuffer name to render to. */
    public final int getWriteFramebuffer() { return fbName; }
    /** Returns the framebuffer name to read from. Depending on multisampling, this may be a different framebuffer. */
    public final int getReadFramebuffer() {
        return 0 < samples ? ( null != samplingSink ? samplingSink.getReadFramebuffer() : 0 ) : fbName;
    }
    public final int getDefaultReadBuffer() { return GL.GL_COLOR_ATTACHMENT0; }
    /** Return the number of attached {@link Colorbuffer}s */
    public final int getColorbufferCount() { return colorbufferCount; }
    /** Return the number of attached {@link TextureAttachment}s */
    public final int getTextureAttachmentCount() { return textureAttachmentCount; }
    /** Return the stencil {@link RenderAttachment} attachment, if exist. Maybe share the same {@link Attachment#getName()} as {@link #getDepthAttachment()}, if packed depth-stencil is being used. */
    public final RenderAttachment getStencilAttachment() { return stencil; }
    /** Return the depth {@link RenderAttachment} attachment. Maybe share the same {@link Attachment#getName()} as {@link #getStencilAttachment()}, if packed depth-stencil is being used. */
    public final RenderAttachment getDepthAttachment() { return depth; }

    /** Return the complete multisampling {@link FBObject} sink, if using multisampling. */
    public final FBObject getSamplingSinkFBO() { return samplingSink; }

    /** Return the multisampling {@link Colorbuffer} sink, if using multisampling. */
    public final Colorbuffer getSamplingSink() { return samplingColorSink; }

    /**
     * Returns <code>true</code> if the multisampling colorbuffer (msaa-buffer)
     * has been flagged dirty by a previous call of {@link #bind(GL)},
     * otherwise <code>false</code>.
     */
    public final boolean isSamplingBufferDirty() { return samplingSinkDirty; }

    /**
     * Returns <code>true</code> if size, sample-count or any attachment of this instance
     * or its {@link #getSamplingSink() sampling-sink} has been modified since last {@link #syncSamplingSink(GL) sync},
     * {@link #use(GL, TextureAttachment) use}, {@link #reset(GL, int, int, int) reset}
     * or {@link #resetSamplingSink(GL) resetSamplingSink}.
     * <p>
     * Otherwise method returns <code>false</code>.
     * </p>
     */
    public final boolean isModified() { return modified || ( null != samplingSink && samplingSink.modified ); }

    int objectHashCode() { return super.hashCode(); }

    @Override
    public final String toString() {
        final String caps = null != colorbufferAttachments ? Arrays.asList(colorbufferAttachments).toString() : null ;
        return "FBO[name r/w "+fbName+"/"+getReadFramebuffer()+", init "+initialized+", bound "+bound+", size "+width+"x"+height+
               ", samples "+samples+"/"+maxSamples+", modified "+modified+"/"+isModified()+", depth "+depth+", stencil "+stencil+
               ", colorbuffer attachments: "+colorbufferCount+"/"+maxColorAttachments+", with "+textureAttachmentCount+" textures"+
               ": "+caps+", msaa["+samplingColorSink+", hasSink "+(null != samplingSink)+
               ", dirty "+samplingSinkDirty+"], state "+getStatusString()+", obj "+toHexString(objectHashCode())+"]";
    }

    private final void updateStatus(final GL gl) {
        if( 0 == fbName ) {
            vStatus = -1;
        } else {
            vStatus = gl.glCheckFramebufferStatus(GL.GL_FRAMEBUFFER);
        }
    }
}