aboutsummaryrefslogtreecommitdiffstats
path: root/src/javax/media/j3d/MasterControl.java
blob: 0d7af6673e27141da68adae5b1eb39d00ee764eb (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
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
/*
 * Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 *
 */

/*
 * Portions of this code were derived from work done by the Blackdown
 * group (www.blackdown.org), who did the initial Linux implementation
 * of the Java 3D API.
 */

package javax.media.j3d;

import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.logging.Level;
import java.util.logging.Logger;

class MasterControl {

    /**
     * Options for the runMonitor
     */
    static final int CHECK_FOR_WORK = 0;
    static final int SET_WORK       = 1;
    static final int RUN_THREADS    = 2;
    static final int THREAD_DONE    = 3;
    static final int SET_WORK_FOR_REQUEST_RENDERER   = 5;
    static final int RUN_RENDERER_CLEANUP            = 6;

    // The thread states for MC
    static final int SLEEPING            = 0;
    static final int RUNNING             = 1;
    static final int WAITING_FOR_THREADS = 3;
    static final int WAITING_FOR_CPU     = 4;
    static final int WAITING_FOR_RENDERER_CLEANUP = 5;

    // Constants used in renderer thread argument
    static final Integer REQUESTRENDER = new Integer(Renderer.REQUESTRENDER);
    static final Integer RENDER = new Integer(Renderer.RENDER);
    static final Integer SWAP = new Integer(Renderer.SWAP);

    // Constants used for request from user threads
    static final Integer ACTIVATE_VIEW = new Integer(1);
    static final Integer DEACTIVATE_VIEW = new Integer(2);
    static final Integer START_VIEW = new Integer(3);
    static final Integer STOP_VIEW = new Integer(4);
    static final Integer REEVALUATE_CANVAS = new Integer(5);
    static final Integer UNREGISTER_VIEW = new Integer(6);
    static final Integer PHYSICAL_ENV_CHANGE = new Integer(7);
    static final Integer INPUTDEVICE_CHANGE = new Integer(8);
    static final Integer EMPTY_UNIVERSE = new Integer(9);
    static final Integer START_RENDERER = new Integer(10);
    static final Integer STOP_RENDERER = new Integer(11);
    static final Integer RENDER_ONCE = new Integer(12);
    static final Integer FREE_CONTEXT = new Integer(13);
    static final Integer FREE_DRAWING_SURFACE = new Integer(14);
    static final Integer FREE_MESSAGE = new Integer(15);
    static final Integer RESET_CANVAS = new Integer(16);
    static final Integer GETBESTCONFIG = new Integer(17);
    static final Integer ISCONFIGSUPPORT = new Integer(18);
    static final Integer SET_GRAPHICSCONFIG_FEATURES = new Integer(19);
    static final Integer SET_QUERYPROPERTIES = new Integer(20);
    static final Integer SET_VIEW = new Integer(21);

    // Developer logger for reporting informational messages; see getDevLogger()
    private static boolean devLoggerEnabled = false;
    private static Logger devLogger;

    // Stats logger for reporting runtime statistics; see getStatsLogger()
    private static boolean statsLoggerEnabled = false;
    private static Logger statsLogger;

    // Core logger for reporting internal errors, warning, and
    // informational messages; see getCoreLogger()
    private static boolean coreLoggerEnabled = false;
    private static Logger coreLogger;

    // Flag indicating that the rendering pipeline libraries are loaded
    private static boolean librariesLoaded = false;

    /**
     * reference to MasterControl thread
     */
    private MasterControlThread mcThread = null;

    /**
     * The list of views that are currently registered
     */
    private UnorderList views = new UnorderList(1, View.class);


    /**
     * by MIK OF CLASSX
     *
     * the flag to indicate whether the background of the offscreen
     * canvas must be transparent or not false by default
     */
    boolean transparentOffScreen = false;

    /**
     * Flag to indicate whether Pbuffers are used for off-screen
     * rendering; true by default.  Set by the "j3d.usePbuffer"
     * property, When this flag is set to false, Bitmap (Windows) or
     * Pixmap (UNIX) rendering will be used
     */
    boolean usePbuffer = true;

    /**
     * Flag to indicate whether should renderer view frustum culling is done;
     * true by default.
     * Set by the -Dj3d.viewFrustumCulling property, When this flag is
     * set to false, the renderer view frustum culling is turned off.
     */
    boolean viewFrustumCulling = true;

    /**
     * the flag to indicate whether the geometry should be locked or not
     */

    private boolean lockGeometry = false;

    /**
     * The number of registered views that are active
     */
    private int numActiveViews = 0;

    /**
     * The list of active universes get from View
     */
    private UnorderList activeUniverseList = new UnorderList(VirtualUniverse.class);

    /**
     * The list of universes register from View
     */
    private UnorderList regUniverseList = new UnorderList(VirtualUniverse.class);

    /**
     * A lock used for accessing time structures.
     */
    private Object timeLock = new Object();


    /**
     * The current "time" value
     */
    private long time = 0;

    /**
     * Use to assign threadOpts in Renderer thread.
     */
    private long waitTimestamp = 0;

    /**
     * The current list of work threads
     */
    private UnorderList stateWorkThreads =
                               new UnorderList(J3dThreadData.class);
    private UnorderList renderWorkThreads =
                               new UnorderList(J3dThreadData.class);
    private UnorderList requestRenderWorkThreads =
			       new UnorderList(J3dThreadData.class);

    /**
     * The current list of work threads
     */
    private UnorderList renderThreadData = new UnorderList(J3dThreadData.class);

    /**
     * The list of input device scheduler thread
     */
    private UnorderList inputDeviceThreads =
                             new UnorderList(1, InputDeviceScheduler.class);

    /**
     * A flag that is true when the thread lists need updating
     */
    private boolean threadListsChanged;


    /**
     * Markers for the last transform structure update thread
     * and the last update thread.
     */
    private int lastTransformStructureThread = 0;
    private int lastStructureUpdateThread = 0;

    /**
     * The current time snapshots
     */
    private long currentTime;

    // Only one Timer thread in the system.
    TimerThread timerThread;

    // Only one Notification thread in the system.
    private NotificationThread notificationThread;

    /**
     * This flag indicates that MC is running
     */
    volatile boolean running = true;

    /**
     * This flag indicates that MC has work to do
     */
    private boolean workToDo = false;

    /**
     * This flag indicates that there is work for requestRenderer
     */
    private boolean requestRenderWorkToDo = false;

   /**
     * The number of THREAD_DONE messages pending
     */
    private int threadPending = 0;
    private int renderPending = 0;
    private int statePending = 0;

    /**
     * State variables for work lists
     */
    private boolean renderWaiting = false;
    private boolean stateWaiting = false;

    /**
     * The current state of the MC thread
     */
    private int state = SLEEPING;

    // time for sleep in order to met the minimum frame duration
    private long sleepTime = 0;


    /**
     * The number of cpu's Java 3D may use
     */
    private int cpuLimit;

    /**
     * A list of mirror objects to be updated
     */
    private UnorderList mirrorObjects = new UnorderList(ObjectUpdate.class);

    /**
     * The renderingAttributesStructure for updating node component
     * objects
     */
    private RenderingAttributesStructure renderingAttributesStructure =
                        new RenderingAttributesStructure();

    /**
     * The default rendering method
     */
    private DefaultRenderMethod defaultRenderMethod = null;

    /**
     * The text3D rendering method
     */
    private Text3DRenderMethod text3DRenderMethod = null;

    /**
     * The vertex array rendering method
     */
    private VertexArrayRenderMethod vertexArrayRenderMethod = null;

    /**
     * The displayList rendering method
     */
    private DisplayListRenderMethod displayListRenderMethod = null;

    /**
     * The compressed geometry rendering method
     */
    private CompressedGeometryRenderMethod compressedGeometryRenderMethod = null;

    /**
     * The oriented shape3D rendering method
     */
    private OrientedShape3DRenderMethod orientedShape3DRenderMethod = null;

    /**
     * This is the start time upon which alpha's and behaviors
     * are synchronized to. It is initialized once, the first time
     * that a MasterControl object is created.
     */
    static long systemStartTime = 0L;

    // This is a time stamp used when context is created
    private long contextTimeStamp = 0;

    // This is an array of  canvasIds in used
    private boolean[] canvasIds = null;
    private int canvasFreeIndex = 0;
    private Object canvasIdLock = new Object();

    // This is a counter for rendererBit
    private int rendererCount = 0;

    // Flag that indicates whether to shared display context or not
    boolean isSharedCtx = false;

    // Flag that tells us to use NV_register_combiners
    boolean useCombiners = false;

    // Flag that indicates whether compile is disabled or not
    boolean disableCompile = false;

    // Flag that indicates whether or not compaction occurs
    boolean doCompaction = true;

    // Flag that indicates whether separate specular color is disabled or not
    boolean disableSeparateSpecularColor = false;

    // Flag that indicates whether DisplayList is used or not
    boolean isDisplayList = true;

    // If this flag is set, then by-ref geometry will not be
    // put in display list
    boolean buildDisplayListIfPossible = false;

    // If this flag is set, then geometry arrays with vertex attributes can
    // be in display list.
    boolean vertexAttrsInDisplayList = false;

    // Issue 249 - flag that indicates whether the soleUser optimization is permitted
    boolean allowSoleUser = false;

    // Issue 266 - Flag indicating whether null graphics configs are allowed
    // Set by -Dj3d.allowNullGraphicsConfig property
    // Setting this flag causes Canvas3D to allow a null GraphicsConfiguration
    // for on-screen canvases. This is only for backward compatibility with
    // legacy applications.
    boolean allowNullGraphicsConfig = false;

    // Issue 239 - Flag indicating whether the stencil buffer is cleared by
    // default each frame when the color and depth buffers are cleared.
    // Note that this is a partial solution, since we eventually want an API
    // to control this.
    boolean stencilClear = false;

    // REQUESTCLEANUP messages argument
    static Integer REMOVEALLCTXS_CLEANUP = new Integer(1);
    static Integer REMOVECTX_CLEANUP     = new Integer(2);
    static Integer REMOVENOTIFY_CLEANUP  = new Integer(3);
    static Integer RESETCANVAS_CLEANUP   = new Integer(4);
    static Integer FREECONTEXT_CLEANUP   = new Integer(5);

    // arguments for renderer resource cleanup run
    Object rendererCleanupArgs[] = {new Integer(Renderer.REQUESTCLEANUP),
				    null, null};


    // Context creation should obtain this lock, so that
    // first_time and all the extension initilialization
    // are done in the MT safe manner
    Object contextCreationLock = new Object();

    // Flag that indicates whether to lock the DSI while rendering
    boolean doDsiRenderLock = false;

    // Flag that indicates the pre-1.5 behavior of enforcing power-of-two
    // textures. If set, then any non-power-of-two textures will throw an
    // exception.
    boolean enforcePowerOfTwo = false;

    // Flag that indicates whether the framebuffer is sharing the
    // Z-buffer with both the left and right eyes when in stereo mode.
    // If this is true, we need to clear the Z-buffer between rendering
    // to the left and right eyes.
    boolean sharedStereoZBuffer = true;

    // True to disable all underlying multisampling API so it uses
    // the setting in the driver.
    boolean implicitAntialiasing = false;

    // False to disable compiled vertex array extensions if support
    boolean isCompiledVertexArray = true;

    // Number of reserved vertex attribute locations for GLSL (must be at
    // least 1).
    // Issue 269 - need to reserve up to 6 vertex attribtue locations to ensure
    // that we don't collide with a predefined gl_* attribute on nVidia cards.
    int glslVertexAttrOffset = 6;

    // Hashtable that maps a GraphicsDevice to its associated
    // Screen3D--this is only used for on-screen Canvas3Ds
    Hashtable<GraphicsDevice, Screen3D> deviceScreenMap = new Hashtable<GraphicsDevice, Screen3D>();

    // Use to store all requests from user threads.
    UnorderList requestObjList = new UnorderList();
    private UnorderList requestTypeList = new UnorderList(Integer.class);

    // Temporary storage to store stop request for requestViewList
    private UnorderList tempViewList = new UnorderList();
    private UnorderList renderOnceList = new UnorderList();

    // This flag is true when there is pending request
    // i.e. false when the above requestxxx Lists are all empty.
    private boolean pendingRequest = false;

    // Root ThreadGroup for creating Java 3D threads
    private static ThreadGroup rootThreadGroup;

    // Thread priority for all Java 3D threads
    private static int threadPriority;

    static private Object mcThreadLock = new Object();

	private ArrayList<View> timestampUpdateList = new ArrayList<View>(3);

    private UnorderList freeMessageList = new UnorderList(8);

    // Maximum number of lights
    int maxLights;

    // Set by the -Dj3d.sortShape3DBounds property, When this flag is
    // set to true, the bounds of the Shape3D node will be used in
    // place of the computed GeometryArray bounds for transparency
    // sorting for those Shape3D nodes whose boundsAutoCompute
    // attribute is set to false.
    boolean sortShape3DBounds = false;

    //Set by -Dj3d.forceReleaseView property.
    //Setting this flag as true disables the bug fix 4267395 in View deactivate().
    //The bug 4267395 can lock-up *some* systems, but the bug fix can
    //produce memory leaks in applications which creates and destroy Canvas3D
    //from time to time.
    //Set as true if you have memory leaks after disposing Canvas3D.
    //Default false value does affect Java3D View dispose behavior.
    boolean forceReleaseView = false;

    // Issue 480: Cache the bounds of nodes so that getBounds does not
    // recompute the boounds of the entire graph per call
    boolean cacheAutoComputedBounds = false;

    // issue 544
    boolean useBoxForGroupBounds = false;

    /**
     * Constructs a new MasterControl object.  Note that there is
     * exatly one MasterControl object, created statically by
     * VirtualUniverse.
     */
    MasterControl() {
        assert librariesLoaded;

        // Initialize the start time upon which alpha's and behaviors
        // are synchronized to (if it isn't already set).
        if (systemStartTime == 0L) {
            systemStartTime = J3dClock.currentTimeMillis();
        }

	if(J3dDebug.devPhase) {
	    // Check to see whether debug mode is allowed
	    J3dDebug.debug = getBooleanProperty("j3d.debug", false,
						"J3dDebug.debug");
	}

	// Check to see whether shared contexts are allowed
	isSharedCtx = getBooleanProperty("j3d.sharedctx", isSharedCtx, "shared contexts");

	doCompaction = getBooleanProperty("j3d.docompaction", doCompaction,
					  "compaction");

	// by MIK OF CLASSX
	transparentOffScreen = getBooleanProperty("j3d.transparentOffScreen", transparentOffScreen, "transparent OffScreen");

	usePbuffer = getBooleanProperty("j3d.usePbuffer",
					usePbuffer,
					"Off-screen Pbuffer");

	viewFrustumCulling = getBooleanProperty("j3d.viewFrustumCulling", viewFrustumCulling,"View frustum culling in the renderer is");

	sortShape3DBounds =
	    getBooleanProperty("j3d.sortShape3DBounds", sortShape3DBounds,
			       "Shape3D bounds enabled for transparency sorting",
			       "Shape3D bounds *ignored* for transparency sorting");

	forceReleaseView =
	    getBooleanProperty("j3d.forceReleaseView", forceReleaseView,
			       "forceReleaseView  after Canvas3D dispose enabled",
			       "forceReleaseView  after Canvas3D dispose disabled");

// FIXME: GL_NV_register_combiners
//	useCombiners = getBooleanProperty("j3d.usecombiners", useCombiners,
//					  "Using NV_register_combiners if available",
//					  "NV_register_combiners disabled");

	if (getProperty("j3d.disablecompile") != null) {
	    disableCompile = true;
	    System.err.println("Java 3D: BranchGroup.compile disabled");
	}

	if (getProperty("j3d.disableSeparateSpecular") != null) {
	    disableSeparateSpecularColor = true;
	    System.err.println("Java 3D: separate specular color disabled if possible");
	}

	isDisplayList = getBooleanProperty("j3d.displaylist", isDisplayList,
					   "display list");

	implicitAntialiasing =
	    getBooleanProperty("j3d.implicitAntialiasing",
			       implicitAntialiasing,
			       "implicit antialiasing");

	isCompiledVertexArray =
	    getBooleanProperty("j3d.compiledVertexArray",
			       isCompiledVertexArray,
			       "compiled vertex array");

        boolean j3dOptimizeSpace =
	    getBooleanProperty("j3d.optimizeForSpace", true,
			       "optimize for space");

        if (isDisplayList) {
            // Build Display list for by-ref geometry
            // ONLY IF optimizeForSpace is false
            if (!j3dOptimizeSpace) {
                buildDisplayListIfPossible = true;
            }

            // Build display lists for geometry with vertex attributes
            // ONLY if we are in GLSL mode and GLSL shaders are available
            vertexAttrsInDisplayList = true;
        }

        // Check to see whether Renderer can run without DSI lock
	doDsiRenderLock = getBooleanProperty("j3d.renderLock",
					     doDsiRenderLock,
					     "render lock");

        // Check to see whether we enforce power-of-two textures
        enforcePowerOfTwo = getBooleanProperty("j3d.textureEnforcePowerOfTwo",
					       enforcePowerOfTwo,
					       "checking power-of-two textures");

        // Issue 249 - check to see whether the soleUser optimization is permitted
        allowSoleUser = getBooleanProperty("j3d.allowSoleUser",
					   allowSoleUser,
					   "sole-user mode");

        // Issue 266 - check to see whether null graphics configs are allowed
        allowNullGraphicsConfig = getBooleanProperty("j3d.allowNullGraphicsConfig",
						     allowNullGraphicsConfig,
						     "null graphics configs");

        // Issue 239 - check to see whether per-frame stencil clear is enabled
        stencilClear = getBooleanProperty("j3d.stencilClear",
                                          stencilClear,
                                          "per-frame stencil clear");

        // Check to see if stereo mode is sharing the Z-buffer for both eyes.
	sharedStereoZBuffer =
	    getBooleanProperty("j3d.sharedstereozbuffer",
			       sharedStereoZBuffer,
			       "shared stereo Z buffer");

	// Get the maximum number of concurrent threads (CPUs)
	final int defaultThreadLimit = getNumberOfProcessors() + 1;
	Integer threadLimit = java.security.AccessController.doPrivileged(
	new java.security.PrivilegedAction<Integer>() {
		@Override
		public Integer run() {
			return Integer.getInteger("j3d.threadLimit", defaultThreadLimit);
		}
	});

	cpuLimit = threadLimit.intValue();
	if (cpuLimit < 1)
	    cpuLimit = 1;
	if (J3dDebug.debug || cpuLimit != defaultThreadLimit) {
	    System.err.println("Java 3D: concurrent threadLimit = " +
			       cpuLimit);
	}

	// Get the input device scheduler sampling time
	Integer samplingTime = java.security.AccessController.doPrivileged(
	new java.security.PrivilegedAction<Integer>() {
		@Override
		public Integer run() {
			return Integer.getInteger("j3d.deviceSampleTime", 0);
		}
	});

	if (samplingTime.intValue() > 0) {
	    InputDeviceScheduler.samplingTime =
		samplingTime.intValue();
	    System.err.println("Java 3D: Input device sampling time = "
			       + samplingTime + " ms");
	}

	// Get the glslVertexAttrOffset
	final int defaultGLSLVertexAttrOffset = glslVertexAttrOffset;
	Integer vattrOffset = java.security.AccessController.doPrivileged(
	new java.security.PrivilegedAction<Integer>() {
		@Override
		public Integer run() {
			return Integer.getInteger("j3d.glslVertexAttrOffset",
					defaultGLSLVertexAttrOffset);
		}
	});

	glslVertexAttrOffset = vattrOffset.intValue();
        if (glslVertexAttrOffset < 1) {
            glslVertexAttrOffset = 1;
        }
	if (J3dDebug.debug || glslVertexAttrOffset != defaultGLSLVertexAttrOffset) {
	    System.err.println("Java 3D: glslVertexAttrOffset = " +
			       glslVertexAttrOffset);
	}

        // Issue 480 : Cache bounds returned by getBounds()
        cacheAutoComputedBounds =
                getBooleanProperty("j3d.cacheAutoComputeBounds",
                cacheAutoComputedBounds,
                "Cache AutoCompute Bounds, accelerates getBounds()");

        // Issue 544
        useBoxForGroupBounds =
                getBooleanProperty("j3d.useBoxForGroupBounds",
                useBoxForGroupBounds,
                "Use of BoundingBox for group geometric bounds");

        // Check for obsolete properties
        String[] obsoleteProps = {
            "j3d.backgroundtexture",
            "j3d.forceNormalized",
            "j3d.g2ddrawpixel",
            "j3d.simulatedMultiTexture",
            "j3d.useFreeLists",
        };
        for (int i = 0; i < obsoleteProps.length; i++) {
            if (getProperty(obsoleteProps[i]) != null) {
                System.err.println("Java 3D: " + obsoleteProps[i] + " property ignored");
            }
        }

	// Get the maximum Lights
	maxLights = Pipeline.getPipeline().getMaximumLights();

	// create the freelists
	FreeListManager.createFreeLists();

	// create an array canvas use registers
	// The 32 limit can be lifted once the
	// resourceXXXMasks in other classes
	// are change not to use integer.
	canvasIds = new boolean[32];
	for(int i=0; i<canvasIds.length; i++) {
	    canvasIds[i] = false;
	}
        canvasFreeIndex = 0;
    }

    private static boolean initLogger(Logger logger, Level defaultLevel) {
        if (logger == null) {
            return false;
        }

        if (defaultLevel != null &&
                logger.getLevel() == null &&
                Logger.getLogger("j3d").getLevel() == null) {

            try {
                // Set default logger level rather than inheriting from system global
                logger.setLevel(defaultLevel);
            } catch (SecurityException ex) {
                System.err.println(ex);
                return false;
            }
        }

        return logger.isLoggable(Level.SEVERE);
    }

    // Called by the static initializer to initialize the loggers
    private static void initLoggers() {
        coreLogger = Logger.getLogger("j3d.core");
        devLogger = Logger.getLogger("j3d.developer");
        statsLogger = Logger.getLogger("j3d.stats");

        java.security.AccessController.doPrivileged(
            new java.security.PrivilegedAction<Object>() {
                @Override
                public Object run() {
                    coreLoggerEnabled = initLogger(coreLogger, null);
                    devLoggerEnabled = initLogger(devLogger, Level.OFF);
                    statsLoggerEnabled = initLogger(statsLogger, Level.OFF);
                    return null;
                }
        });
    }

    /**
     * Get the developer logger -- OFF by default
     *
     * WARNING - for probable incorrect or inconsistent api usage
     * INFO - for informational messages such as performance hints (less verbose than FINE)
     * FINE - for informational messages from inner loops
     * FINER - using default values which may not be optimal
     */
    static Logger getDevLogger() {
        return devLogger;
    }

    static boolean isDevLoggable(Level level) {
        return devLoggerEnabled && devLogger.isLoggable(level);
    }

    /**
     * Get the stats logger -- OFF by default
     *
     * WARNING - statistical anomalies
     * INFO - basic performance stats - not too verbose and minimally intrusive
     * FINE - somewhat verbose and intrusive
     * FINER - more verbose and intrusive
     * FINEST - most verbose and intrusive
     */
    static Logger getStatsLogger() {
        return statsLogger;
    }

    static boolean isStatsLoggable(Level level) {
        return statsLoggerEnabled && statsLogger.isLoggable(level);
    }

    /**
     * Get the core logger -- level is INFO by default
     *
     * SEVERE - Serious internal errors
     * WARNING - Possible internal errors or anomalies
     * INFO - General informational messages
     * FINE - Internal debugging information - somewhat verbose
     * FINER - Internal debugging information - more verbose
     * FINEST - Internal debugging information - most verbose
     */
    static Logger getCoreLogger() {
        return coreLogger;
    }

    static boolean isCoreLoggable(Level level) {
        return coreLoggerEnabled && coreLogger.isLoggable(level);
    }

private static String getProperty(final String prop) {
	return java.security.AccessController.doPrivileged(
		new java.security.PrivilegedAction<String>() {
			@Override
			public String run() {
				return System.getProperty(prop);
			}
		});
}

    static boolean getBooleanProperty(String prop,
					      boolean defaultValue,
					      String trueMsg,
					      String falseMsg) {
	boolean value = defaultValue;
	String propValue = getProperty(prop);

	if (propValue != null) {
	    value = Boolean.valueOf(propValue).booleanValue();
		if (J3dDebug.debug)
			System.err.println("Java 3D: " + (value ? trueMsg : falseMsg));
	}
	return value;
    }

    static boolean getBooleanProperty(String prop,
					      boolean defaultValue,
					      String msg) {
	return getBooleanProperty(prop,
				  defaultValue,
				  (msg + " enabled"),
				  (msg + " disabled"));
    }

    /**
     * Method to create and initialize the rendering Pipeline object,
     * and to load the native libraries needed by Java 3D. This is
     * called by the static initializer in VirtualUniverse <i>before</i>
     * the MasterControl object is created.
     */
    static void loadLibraries() {
        assert !librariesLoaded;

        // Initialize the Pipeline object associated with the
        // renderer specified by the "j3d.rend" system property.
        //
        // XXXX : We should consider adding support for a more flexible,
        // dynamic selection scheme via an API call.

        // Default rendering pipeline is the JOGL pipeline
        Pipeline.Type pipelineType = Pipeline.Type.JOGL;

        final String rendStr = getProperty("j3d.rend");
        if (rendStr == null) {
            // Use default pipeline
        } else if (rendStr.equals("jogl")) {
            pipelineType = Pipeline.Type.JOGL;
        } else if (rendStr.equals("noop")) {
            pipelineType = Pipeline.Type.NOOP;
        } else {
            System.err.println("Java 3D: Unrecognized renderer: " + rendStr);
            // Use default pipeline
        }

        // Construct the singleton Pipeline instance
		Pipeline.createPipeline(pipelineType);

        librariesLoaded = true;
    }


    /**
     * Invoke from InputDeviceScheduler to create an
     * InputDeviceBlockingThread.
     */
    InputDeviceBlockingThread getInputDeviceBlockingThread(
					   final InputDevice device) {

	return java.security.AccessController.doPrivileged(
		new java.security.PrivilegedAction<InputDeviceBlockingThread>() {
			@Override
			public InputDeviceBlockingThread run() {
				synchronized (rootThreadGroup) {
					InputDeviceBlockingThread thread = new InputDeviceBlockingThread(
							rootThreadGroup, device);
					thread.setPriority(threadPriority);
					return thread;
				}
			}
		});
    }

    /**
     * Set thread priority to all threads under Java3D thread group.
     */
    void setThreadPriority(final int pri) {
	synchronized (rootThreadGroup) {
	    threadPriority = pri;
	    java.security.AccessController.doPrivileged(
                new java.security.PrivilegedAction<Object>() {
                    @Override
                    public Object run() {
			Thread list[] = new
			    Thread[rootThreadGroup.activeCount()];
			int count = rootThreadGroup.enumerate(list);
			for (int i=count-1; i >=0; i--) {
			    list[i].setPriority(pri);
			}
			return null;
		    }
	    });
	}
    }


    /**
     * Return Java3D thread priority
     */
    int getThreadPriority() {
	return threadPriority;
    }

    /**
     * This returns the a unused renderer bit
     */
    int getRendererBit() {
        return (1 << rendererCount++);
    }


    /**
     * This returns the a unused renderer bit
     */
    int getRendererId() {
        return rendererCount++;
    }

    /**
     * This returns a context creation time stamp
     * Note: this has to be called under the contextCreationLock
     */
    long getContextTimeStamp() {
	return (++contextTimeStamp);
    }


    /**
     * This returns the a unused displayListId
     */
    Integer getDisplayListId() {
        return (Integer) FreeListManager.getObject(FreeListManager.DISPLAYLIST);
    }

    void freeDisplayListId(Integer id) {
	FreeListManager.freeObject(FreeListManager.DISPLAYLIST, id);
    }

    int getCanvasId() {
        int i;

	synchronized(canvasIdLock) {
	    // Master control need to keep count itself
	    for(i=canvasFreeIndex; i<canvasIds.length; i++) {
		if(canvasIds[i] == false)
		    break;
	    }

	    if (i >= canvasIds.length) {
                throw new RuntimeException("Cannot render to more than 32 Canvas3Ds");
	    }

	    canvasIds[i] = true;
	    canvasFreeIndex = i + 1;
	}

        return i;

    }

    void freeCanvasId(int canvasId) {
        // Valid range is [0, 31]
	synchronized(canvasIdLock) {

	    canvasIds[canvasId] = false;
	    if(canvasFreeIndex > canvasId) {
		canvasFreeIndex = canvasId;
	    }
	}
    }


    /**
     * Create a Renderer if it is not already done so.
     * This is used for GraphicsConfigTemplate3D passing
     * graphics call to RequestRenderer, and for creating
     * an off-screen buffer for an off-screen Canvas3D.
     */
    private Renderer createRenderer(GraphicsConfiguration gc) {
	final GraphicsDevice gd = gc.getDevice();

	Renderer rdr = Screen3D.deviceRendererMap.get(gd);
	if (rdr != null) {
	    return rdr;
	}


	java.security.AccessController.doPrivileged(
	     new java.security.PrivilegedAction<Object>() {
                    @Override
                    public Object run() {
			Renderer r;
		        synchronized (rootThreadGroup) {
			    r = new Renderer(rootThreadGroup);
			    r.initialize();
			    r.setPriority(threadPriority);
			    Screen3D.deviceRendererMap.put(gd, r);
			}
			return null;
		   }
	});

	threadListsChanged = true;

	return Screen3D.deviceRendererMap.get(gd);
    }

    /**
     * Post the request in queue
     */
    void postRequest(Integer type, Object obj) {

	synchronized (mcThreadLock) {
	    synchronized (requestObjList) {
		if (mcThread == null) {
		    if ((type == ACTIVATE_VIEW) ||
			(type == GETBESTCONFIG) ||
			(type == SET_VIEW) ||
			(type == ISCONFIGSUPPORT) ||
			(type == SET_QUERYPROPERTIES) ||
			(type == SET_GRAPHICSCONFIG_FEATURES)) {
			createMasterControlThread();
			requestObjList.add(obj);
			requestTypeList.add(type);
			pendingRequest = true;
		    } else if (type == EMPTY_UNIVERSE) {
			destroyUniverseThreads((VirtualUniverse) obj);
		    } else if (type == STOP_VIEW) {
			View v = (View) obj;
			v.stopViewCount = -1;
			v.isRunning = false;
		    } else if (type == STOP_RENDERER) {
			if (obj instanceof Canvas3D) {
			    ((Canvas3D) obj).isRunningStatus = false;
			} else {
			    ((Renderer) obj).userStop = true;
			}
		    } else if (type == UNREGISTER_VIEW) {
			((View) obj).doneUnregister = true;
		    } else {
			requestObjList.add(obj);
			requestTypeList.add(type);
			pendingRequest = true;
		    }
		} else {
		    requestObjList.add(obj);
		    requestTypeList.add(type);
		    pendingRequest = true;
		}
	    }
	}

	setWork();
    }




    /**
     * This procedure is invoked when isRunning is false.
     * Return true when there is no more pending request so that
     * Thread can terminate. Otherwise we have to recreate
     * the MC related threads.
     */
    boolean mcThreadDone() {
	synchronized (mcThreadLock) {
	    synchronized (requestObjList) {
		if (!pendingRequest) {
		    mcThread = null;
		    if (renderingAttributesStructure.updateThread !=
			null) {
			renderingAttributesStructure.updateThread.finish();
			renderingAttributesStructure.updateThread =
			    null;
		    }
		    renderingAttributesStructure = new RenderingAttributesStructure();
		    if (timerThread != null) {
			timerThread.finish();
			timerThread = null;
		    }
		    if (notificationThread != null) {
			notificationThread.finish();
			notificationThread = null;
		    }
		    requestObjList.clear();
		    requestTypeList.clear();
		    return true;
		}
		running = true;
		createMCThreads();
		return false;
	    }
	}
    }

    /**
     * This method increments and returns the next time value
     * timeLock must get before this procedure is invoked
     */
    final long getTime() {
	return (time++);
    }


    /**
     * This takes a given message and parses it out to the structures and
     * marks its time value.
     */
    void processMessage(J3dMessage message) {

        synchronized (timeLock) {
	    message.time = getTime();
	    sendMessage(message);
	}
	setWork();
    }

    /**
     * This takes an array of messages and parses them out to the structures and
     * marks the time value. Make sure, setWork() is done at the very end
     * to make sure all the messages will be processed in the same frame
     */
    void processMessage(J3dMessage[] messages) {

        synchronized (timeLock) {
	    long time = getTime();

	    for (int i = 0; i < messages.length; i++) {
		messages[i].time = time;
		sendMessage(messages[i]);
	    }
	}
	setWork();
    }

    /**
     * This takes the specified notification message and sends it to the
     * notification thread for processing.
     */
    void sendNotification(J3dNotification notification) {
        notificationThread.addNotification(notification);
    }

    /**
     * Create and start the MasterControl Thread.
     */
    void createMasterControlThread() {
        // Issue 364: don't create master control thread if already created
        if (mcThread != null) {
            return;
        }

	running = true;
	workToDo = true;
	state = RUNNING;
	java.security.AccessController.doPrivileged(
	    new java.security.PrivilegedAction<Object>() {
                @Override
                public Object run() {
		    synchronized (rootThreadGroup) {
			mcThread = new
			    MasterControlThread(rootThreadGroup);
			mcThread.setPriority(threadPriority);
		    }
		    return null;
		}
	});
    }

    // assuming the timeLock is already acquired

    /**
     * Send a message to another Java 3D thread.
     */
    void sendMessage(J3dMessage message) {

 	  synchronized (message) {
	    VirtualUniverse u = message.universe;
	    int targetThreads = message.threads;

            if (isCoreLoggable(Level.FINEST)) {
                dumpMessage("sendMessage", message);
            }

	    if ((targetThreads & J3dThread.UPDATE_RENDERING_ATTRIBUTES) != 0) {
		renderingAttributesStructure.addMessage(message);
	    }

	    // GraphicsContext3D send message with universe = null
	    if (u != null) {
		if ((targetThreads & J3dThread.UPDATE_GEOMETRY) != 0) {
		    u.geometryStructure.addMessage(message);
		}
		if ((targetThreads & J3dThread.UPDATE_TRANSFORM) != 0) {
		    u.transformStructure.addMessage(message);
		}
		if ((targetThreads & J3dThread.UPDATE_BEHAVIOR) != 0) {
		    u.behaviorStructure.addMessage(message);
		}
		if ((targetThreads & J3dThread.UPDATE_SOUND) != 0) {
		    u.soundStructure.addMessage(message);
		}
		if ((targetThreads & J3dThread.UPDATE_RENDERING_ENVIRONMENT) != 0) {
		    u.renderingEnvironmentStructure.addMessage(message);
		}
	    }

            if ((targetThreads & J3dThread.SOUND_SCHEDULER) != 0) {
                // Note that we don't check for active view
                if (message.view != null && message.view.soundScheduler != null ) {
                    // This make sure that message won't lost even
                    // though this view not yet register
                    message.view.soundScheduler.addMessage(message);
                } else {
		    synchronized (views) {
			View v[] = (View []) views.toArray(false);
			int i = views.arraySize()-1;
			if (u == null) {
			    while (i>=0) {
				v[i--].soundScheduler.addMessage(message);
			    }
			} else {
			    while (i>=0) {
				if (v[i].universe == u) {
				    v[i].soundScheduler.addMessage(message);
				}
				i--;
			    }
			}
		    }
                }
            }

	    if ((targetThreads & J3dThread.UPDATE_RENDER) != 0) {
		// Note that we don't check for active view
		if (message.view != null && message.view.renderBin != null) {
		    // This make sure that message won't lost even
		    // though this view not yet register
		    message.view.renderBin.addMessage(message);
		} else {
		    synchronized (views) {
			View v[] = (View []) views.toArray(false);
			int i = views.arraySize()-1;
			if (u == null) {
			    while (i>=0) {
				v[i--].renderBin.addMessage(message);
			    }
			}
			else {
			    while (i>=0) {
				if (v[i].universe == u) {
				    v[i].renderBin.addMessage(message);
				}
				i--;
			    }
			}
		    }
		}
	    }

	    if (message.getRefcount() == 0) {
		message.clear();
	    }
	  }
    }


    /**
     * Send a message to another Java 3D thread.
     * This variant is only call by TimerThread for Input Device Scheduler
     * or to redraw all View for RenderThread
     */
    void sendRunMessage(int targetThreads) {

	synchronized (timeLock) {

	    long time = getTime();

	    if ((targetThreads & J3dThread.INPUT_DEVICE_SCHEDULER) != 0) {
		synchronized (inputDeviceThreads) {
		    InputDeviceScheduler ds[] = (InputDeviceScheduler [])
			inputDeviceThreads.toArray(false);
		    for (int i=inputDeviceThreads.size()-1; i >=0; i--) {
			if (ds[i].physicalEnv.activeViewRef > 0) {
			    ds[i].getThreadData().lastUpdateTime =
				time;
			}
		    }

		    // timerThread instance in MC will set to null in
		    // destroyUniverseThreads() so we need to check if
		    // TimerThread kick in to sendRunMessage() after that.
		    // It happens because TimerThread is the only thread run
		    // asychronizously with MasterControl thread.

		    if (timerThread != null) {
			// Notify TimerThread to wakeup this procedure
			// again next time.
			timerThread.addInputDeviceSchedCond();
		    }
		}
	    }
	    if ((targetThreads & J3dThread.RENDER_THREAD) != 0) {
		synchronized (renderThreadData) {
		    J3dThreadData[] threads = (J3dThreadData [])
			renderThreadData.toArray(false);
		    int i=renderThreadData.arraySize()-1;
		    J3dThreadData thr;
		    while (i>=0) {
			thr = threads[i--];
			if ( thr.view.renderBinReady) {
			    thr.lastUpdateTime = time;
			}
		    }
		}
	    }
	}
	setWork();
    }

    /**
     * Send a message to another Java 3D thread.
     * This variant is only call by TimerThread for Sound Scheduler
     */
    void sendRunMessage(long waitTime, View view, int targetThreads) {

	synchronized (timeLock) {

	    long time = getTime();

	    if ((targetThreads & J3dThread.SOUND_SCHEDULER) != 0) {
		if (view.soundScheduler != null)  {
		    view.soundScheduler.threadData.lastUpdateTime = time;
		}
		// wakeup this procedure next time
		// QUESTION: waitTime calculated some milliseconds BEFORE
		//     this methods getTime() called - shouldn't actual
		//     sound Complete time be passed by SoundScheduler
		// QUESTION: will this wake up only soundScheduler associated
		//     with this view?? (since only it's lastUpdateTime is set)
		//     or all soundSchedulers??
		timerThread.addSoundSchedCond(time+waitTime);
	    }
	}
	setWork();
    }

    /**
     * Send a message to another Java 3D thread.
     * This variant is only called to update Render Thread
     */
    void sendRunMessage(View v, int targetThreads) {

	synchronized (timeLock) {
	    long time = getTime();

	    if ((targetThreads & J3dThread.RENDER_THREAD) != 0) {
		synchronized (renderThreadData) {
		    J3dThreadData[] threads = (J3dThreadData [])
			renderThreadData.toArray(false);
		    int i=renderThreadData.arraySize()-1;
		    J3dThreadData thr;
		    while (i>=0) {
			thr = threads[i--];
			if (thr.view == v && v.renderBinReady) {
			    thr.lastUpdateTime = time;
			}
		    }
		}
	    }
	}
	setWork();
    }


    /**
     * This sends a run message to the given threads.
     */
    void sendRunMessage(VirtualUniverse u, int targetThreads) {
	// We don't sendRunMessage to update structure except Behavior

	synchronized (timeLock) {
	    long time = getTime();

	    if ((targetThreads & J3dThread.BEHAVIOR_SCHEDULER) != 0) {
		if (u.behaviorScheduler != null) {
		    u.behaviorScheduler.getThreadData(null,
						      null).lastUpdateTime = time;
		}
	    }

	    if ((targetThreads & J3dThread.UPDATE_BEHAVIOR) != 0) {
		u.behaviorStructure.threadData.lastUpdateTime = time;
	    }

	    if ((targetThreads & J3dThread.UPDATE_GEOMETRY) != 0) {
		u.geometryStructure.threadData.lastUpdateTime = time;
	    }

	    if ((targetThreads & J3dThread.UPDATE_SOUND) != 0) {
		u.soundStructure.threadData.lastUpdateTime = time;
	    }

	    if ((targetThreads & J3dThread.SOUND_SCHEDULER) != 0) {
		synchronized (views) {
		    View v[] = (View []) views.toArray(false);
		    for (int i= views.arraySize()-1; i >=0; i--) {
			if ((v[i].soundScheduler != null) &&
			    (v[i].universe == u)) {
			    v[i].soundScheduler.threadData.lastUpdateTime = time;
			}
		    }
		}
	    }

	    if ((targetThreads & J3dThread.RENDER_THREAD) != 0) {

		synchronized (renderThreadData) {
		    J3dThreadData[] threads = (J3dThreadData [])
			renderThreadData.toArray(false);
		    int i=renderThreadData.arraySize()-1;
		    J3dThreadData thr;
		    while (i>=0) {
			thr = threads[i--];
			if (thr.view.universe == u && thr.view.renderBinReady) {
			    thr.lastUpdateTime = time;
			}
		    }
		}
	    }
	}

	setWork();
    }


    /**
     * Return a clone of View, we can't access
     * individual element of View after getting the size
     * in separate API call without synchronized views.
     */
    UnorderList cloneView() {
	return (UnorderList) views.clone();
    }

    /**
     * Return true if view is already registered with MC
     */
    boolean isRegistered(View view) {
	return views.contains(view);
    }

    /**
     * This snapshots the time values to be used for this iteration.
     * Note that this method is called without the timeLock held.
     * We must synchronize on timeLock to prevent updating
     * thread.lastUpdateTime from user thread in sendMessage()
     * or sendRunMessage().
     */
    private void updateTimeValues() {
        synchronized (timeLock) {
            int i=0;
            J3dThreadData lastThread=null;
            J3dThreadData thread=null;
            long lastTime = currentTime;

            currentTime = getTime();

            J3dThreadData threads[] = (J3dThreadData [])
                                    stateWorkThreads.toArray(false);
            int size = stateWorkThreads.arraySize();

            while (i<lastTransformStructureThread) {
                thread = threads[i++];

                if ((thread.lastUpdateTime > thread.lastRunTime) &&
                    !thread.thread.userStop) {
                    lastThread = thread;
                    thread.needsRun = true;
                    thread.threadOpts = J3dThreadData.CONT_THREAD;
                    thread.lastRunTime =  currentTime;
                } else {
                    thread.needsRun = false;
                }
            }

            if (lastThread != null) {
                lastThread.threadOpts =  J3dThreadData.WAIT_ALL_THREADS;
                lastThread = null;
            }

            while (i<lastStructureUpdateThread) {
                thread = threads[i++];
                if ((thread.lastUpdateTime > thread.lastRunTime) &&
                    !thread.thread.userStop) {
                    lastThread = thread;
                    thread.needsRun = true;
                    thread.threadOpts = J3dThreadData.CONT_THREAD;
                    thread.lastRunTime = currentTime;
                } else {
                    thread.needsRun = false;
                }
            }
            if (lastThread != null) {
                lastThread.threadOpts = J3dThreadData.WAIT_ALL_THREADS;
                lastThread = null;
            }

            while (i<size) {
                thread = threads[i++];
                if ((thread.lastUpdateTime > thread.lastRunTime) &&
                    !thread.thread.userStop) {
                    lastThread = thread;
                    thread.needsRun = true;
                    thread.threadOpts = J3dThreadData.CONT_THREAD;
                    thread.lastRunTime = currentTime;
                } else {
                    thread.needsRun = false;
                }
            }
            if (lastThread != null) {
                lastThread.threadOpts = J3dThreadData.WAIT_ALL_THREADS;
                lastThread = null;
            }


            threads = (J3dThreadData []) renderWorkThreads.toArray(false);
            size = renderWorkThreads.arraySize();
            View v;
            J3dThreadData lastRunThread = null;
            waitTimestamp++;
            sleepTime = 0L;

            boolean threadToRun = false; // Not currently used

            // Fix for Issue 12: loop through the list of threads, calling
            // computeCycleTime() exactly once per view. This ensures that
            // all threads for a given view see consistent values for
            // isMinCycleTimeAchieve and sleepTime.
            v = null;
            for (i=0; i<size; i++) {
                thread = threads[i];
                if (thread.view != v) {
                    thread.view.computeCycleTime();
                    // Set sleepTime to the value needed to satify the
                    // minimum cycle time of the slowest view
                    if (thread.view.sleepTime > sleepTime) {
                        sleepTime = thread.view.sleepTime;
                    }
                }
                v = thread.view;
            }

            v = null;
            for (i=0; i<size; i++) {
                thread = threads[i];
                if (thread.canvas == null) { // Only for swap thread
                    ((Object []) thread.threadArgs)[3] = null;
                }
                if ((thread.lastUpdateTime > thread.lastRunTime) &&
                    !thread.thread.userStop) {

                    if (thread.thread.lastWaitTimestamp == waitTimestamp) {
                        // This renderer thread is repeated. We must wait
                        // until all previous renderer threads done before
                        // allowing this thread to continue. Note that
                        // lastRunThread can't be null in this case.
                        waitTimestamp++;
                        if (thread.view != v) {
                            // A new View is start
                            v = thread.view;
                            threadToRun = true;
                            lastRunThread.threadOpts =
                                (J3dThreadData.STOP_TIMER |
                                 J3dThreadData.WAIT_ALL_THREADS);
                            ((Object []) lastRunThread.threadArgs)[3] = lastRunThread.view;
                            thread.threadOpts = (J3dThreadData.START_TIMER |
                                                 J3dThreadData.CONT_THREAD);
                        } else {
                            if ((lastRunThread.threadOpts &
                                 J3dThreadData.START_TIMER) != 0) {
                                lastRunThread.threadOpts =
                                    (J3dThreadData.START_TIMER |
                                     J3dThreadData.WAIT_ALL_THREADS);

                            } else {
                                lastRunThread.threadOpts =
                                    J3dThreadData.WAIT_ALL_THREADS;
                            }
                            thread.threadOpts = J3dThreadData.CONT_THREAD;

                        }
                    } else {
                        if (thread.view != v) {
                            v = thread.view;
                            threadToRun = true;
                            // Although the renderer thread is not
                            // repeated. We still need to wait all
                            // previous renderer threads if new View
                            // start.
                            if (lastRunThread != null) {
                                lastRunThread.threadOpts =
                                    (J3dThreadData.STOP_TIMER |
                                     J3dThreadData.WAIT_ALL_THREADS);
                                ((Object []) lastRunThread.threadArgs)[3]
                                    = lastRunThread.view;
                            }
                            thread.threadOpts = (J3dThreadData.START_TIMER |
                                                 J3dThreadData.CONT_THREAD);
                        } else {
                            thread.threadOpts = J3dThreadData.CONT_THREAD;
                        }
                    }
                    thread.thread.lastWaitTimestamp = waitTimestamp;
                    thread.needsRun = true;
                    thread.lastRunTime = currentTime;
                    lastRunThread = thread;
                } else {
                    thread.needsRun = false;
                }
            }


            if (lastRunThread != null) {
                lastRunThread.threadOpts =
                                    (J3dThreadData.STOP_TIMER |
                                     J3dThreadData.WAIT_ALL_THREADS|
                                     J3dThreadData.LAST_STOP_TIMER);
                lockGeometry = true;
                ((Object []) lastRunThread.threadArgs)[3] = lastRunThread.view;
            }  else {
                lockGeometry = false;
            }
        }

        // Issue 275 - go to sleep without holding timeLock
	// Sleep for the amount of time needed to satisfy the minimum
	// cycle time for all views.
	if (sleepTime > 0) {
	    // System.err.println("MasterControl: sleep(" + sleepTime + ")");
	    try {
		Thread.sleep(sleepTime);
	    } catch (InterruptedException e) {
		System.err.println(e);
	    }
	    // System.err.println("MasterControl: done sleeping");
	}
    }

    private void createUpdateThread(J3dStructure structure) {
	final J3dStructure s = structure;

	if (s.updateThread == null) {
	    java.security.AccessController.doPrivileged(
	        new java.security.PrivilegedAction<Object>() {
                   @Override
                   public Object run() {
		       synchronized (rootThreadGroup) {
                           s.updateThread = new StructureUpdateThread(
                   	        rootThreadGroup, s, s.threadType);
			   s.updateThread.setPriority(threadPriority);
		       }
		       return null;
		   }
	    });
	    s.updateThread.initialize();
	    s.threadData.thread = s.updateThread;
	    // This takes into accout for thread that just destroy and
	    // create again. In this case the threadData may receive
	    // message before the thread actually created. We don't want
	    // the currentTime to overwrite the update time of which
	    // is set by threadData when get message.
	    s.threadData.lastUpdateTime = Math.max(currentTime,
						   s.threadData.lastUpdateTime);
	}
    }

    private void emptyMessageList(J3dStructure structure, View v) {
	if (structure != null) {
	    if (v == null) {
		if (structure.threadData != null) {
		    structure.threadData.thread = null;
		}

		if (structure.updateThread != null) {
		    structure.updateThread.structure = null;
		}
		structure.updateThread = null;
	    }
	    boolean otherViewExist = false;
	    if ((v != null) && (v.universe != null)) {
		// Check if there is any other View register with the
		// same universe
		for (int i=views.size()-1; i >= 0; i--) {
		    if (((View) views.get(i)).universe == v.universe) {
			otherViewExist = true;
			break;
		    }
		}
	    }


	    UnorderList mlist = structure.messageList;
	    // Note that message is add at the end of array
	    synchronized (mlist) {
		int size = mlist.size();
		if (size > 0) {
		    J3dMessage mess[] = (J3dMessage []) mlist.toArray(false);
		    J3dMessage m;
		    int i = 0;

		    while (i < size) {
			m = mess[i];
			if ((v == null) || (m.view == v) ||
			    ((m.view == null) && !otherViewExist)) {
			    if (m.type == J3dMessage.INSERT_NODES) {
				// There is another View register request
				// immediately following, so no need
				// to remove message.
				break;
			    }
			    // Some other thread may still using this
			    // message so we should not directly
			    // add this message to free lists
			    m.decRefcount();
			    mlist.removeOrdered(i);
			    size--;
			} else {
			    i++;
			}
		    }
		}
	    }
	}
    }

    private void destroyUpdateThread(J3dStructure structure) {
	// If unregisterView message got before EMPTY_UNIVERSE
	// message, then updateThread is already set to null.
	if (structure.updateThread != null) {
	    structure.updateThread.finish();
	    structure.updateThread.structure = null;
	    structure.updateThread = null;
	}
	structure.threadData.thread = null;
	structure.clearMessages();
    }

    /**
     * This register a View with MasterControl.
     * The View has at least one Canvas3D added to a container.
     */
    private void registerView(View v) {
	final VirtualUniverse univ = v.universe;

	if (views.contains(v) && regUniverseList.contains(univ)) {
	    return;  // already register
	}

	if (timerThread == null) {
	    // This handle the case when MC shutdown and restart in
	    // a series of pending request
	    running = true;
	    createMCThreads();
	}
	// If viewId is null, assign one ..
	v.assignViewId();

	// Create thread if not done before
	createUpdateThread(univ.behaviorStructure);
	createUpdateThread(univ.geometryStructure);
	createUpdateThread(univ.soundStructure);
	createUpdateThread(univ.renderingEnvironmentStructure);
	createUpdateThread(univ.transformStructure);

	// create Behavior scheduler
	J3dThreadData threadData = null;

	if (univ.behaviorScheduler == null) {
	    java.security.AccessController.doPrivileged(
		new java.security.PrivilegedAction<Object>() {
                       @Override
                       public Object run() {
			   synchronized (rootThreadGroup) {
			       univ.behaviorScheduler = new BehaviorScheduler(
						      rootThreadGroup, univ);
			       univ.behaviorScheduler.setPriority(threadPriority);
			   }
			   return null;
		       }
	    });
	    univ.behaviorScheduler.initialize();
	    univ.behaviorScheduler.userStop = v.stopBehavior;
	    threadData = univ.behaviorScheduler.getThreadData(null, null);
	    threadData.thread = univ.behaviorScheduler;
	    threadData.threadType = J3dThread.BEHAVIOR_SCHEDULER;
	    threadData.lastUpdateTime = Math.max(currentTime,
						 threadData.lastUpdateTime);
	}

	createUpdateThread(v.renderBin);
	createUpdateThread(v.soundScheduler);

	if (v.physicalEnvironment != null) {
	    v.physicalEnvironment.addUser(v);
	}
	// create InputDeviceScheduler
	evaluatePhysicalEnv(v);

	regUniverseList.addUnique(univ);
	views.addUnique(v);
    }



    /**
     * This unregister a View with MasterControl.
     * The View no longer has any Canvas3Ds in a container.
     */
    private void unregisterView(View v) {

	if (!views.remove(v)) {
	    v.active = false;
	    v.doneUnregister = true;
	    return; // already unregister
	}

	if (v.active) {
	    viewDeactivate(v);
	}

	if(J3dDebug.devPhase) {
	    J3dDebug.doDebug(J3dDebug.masterControl, J3dDebug.LEVEL_1,
			     "MC: Destroy Sound Scheduler and RenderBin Update thread");
	}

	v.soundScheduler.updateThread.finish();
	v.renderBin.updateThread.finish();
	v.soundScheduler.updateThread = null;
	v.renderBin.updateThread = null;

	// remove VirtualUniverse related threads if Universe
	// is empty
        VirtualUniverse univ = v.universe;

	synchronized (timeLock) {
	    // The reason we need to sync. with timeLock is because we
	    // don't want user thread running sendMessage() to
	    // dispatch it in different structure queue when
	    // part of the structure list is empty at the same time.
	    // This will cause inconsistence in the message reference
	    // count.
	    emptyMessageList(v.soundScheduler, v);
	    emptyMessageList(v.renderBin, v);

	    if (univ.isEmpty()) {
		destroyUniverseThreads(univ);
	    }  else {
		emptyMessageList(univ.behaviorStructure, v);
		emptyMessageList(univ.geometryStructure, v);
		emptyMessageList(univ.soundStructure, v);
		emptyMessageList(univ.renderingEnvironmentStructure, v);
		emptyMessageList(univ.transformStructure, v);
	    }
	}

	if (v.physicalEnvironment != null) {
	    v.physicalEnvironment.removeUser(v);
	}

	// remove all InputDeviceScheduler if this is the last View
	ArrayList<PhysicalEnvironment> list = new ArrayList<PhysicalEnvironment>();
	for (Enumeration<PhysicalEnvironment> e = PhysicalEnvironment.physicalEnvMap.keys(); e.hasMoreElements();) {
		PhysicalEnvironment phyEnv = e.nextElement();
		InputDeviceScheduler sched = PhysicalEnvironment.physicalEnvMap.get(phyEnv);
		boolean phyEnvHasUser = false;
		for (int i = 0; i < phyEnv.users.size(); i++) {
			if (views.contains(phyEnv.users.get(i))) {
				// at least one registered view refer to it.
				phyEnvHasUser = true;
				break;
			}
		}

		if (!phyEnvHasUser) {
			if (J3dDebug.devPhase) {
				J3dDebug.doDebug(J3dDebug.masterControl, J3dDebug.LEVEL_1,
						"MC: Destroy InputDeviceScheduler thread "
								+ sched);
			}
			sched.finish();
			phyEnv.inputsched = null;
			list.add(phyEnv);
		}
	}
	for (int i = 0; i < list.size(); i++) {
		PhysicalEnvironment.physicalEnvMap.remove(list.get(i));
	}

	freeContext(v);

	if (views.isEmpty()) {
	    if(J3dDebug.devPhase) {
		J3dDebug.doDebug(J3dDebug.masterControl, J3dDebug.LEVEL_1,
				 "MC: Destroy all Renderers");
	    }
	    // remove all Renderers if this is the last View
	    for (Enumeration<Renderer> e = Screen3D.deviceRendererMap.elements();
		 e.hasMoreElements(); ) {
		Renderer rdr = e.nextElement();
		Screen3D scr;

		rendererCleanupArgs[2] = REMOVEALLCTXS_CLEANUP;
		runMonitor(RUN_RENDERER_CLEANUP, null, null, null, rdr);
		scr = rdr.onScreen;
		if (scr != null) {
		    if (scr.renderer != null) {
			rendererCleanupArgs[2] = REMOVEALLCTXS_CLEANUP;
			runMonitor(RUN_RENDERER_CLEANUP, null, null,
				   null, scr.renderer);
			scr.renderer = null;
		    }

		}
		scr = rdr.offScreen;
		if (scr != null) {
		    if (scr.renderer != null) {
			rendererCleanupArgs[2] = REMOVEALLCTXS_CLEANUP;
			runMonitor(RUN_RENDERER_CLEANUP, null, null,
				   null, scr.renderer);
			scr.renderer = null;
		    }
		}
		rdr.onScreen = null;
		rdr.offScreen = null;
	    }

	    // cleanup ThreadData corresponds to the view in renderer
	    for (Enumeration<Renderer> e = Screen3D.deviceRendererMap.elements();
		 e.hasMoreElements(); ) {
	    	e.nextElement().cleanup();
	    }
	    // We have to reuse renderer even though MC exit
	    // see bug 4363279
	    //  Screen3D.deviceRendererMap.clear();

	} else {
	    // cleanup ThreadData corresponds to the view in renderer
	    for (Enumeration<Renderer> e = Screen3D.deviceRendererMap.elements();
		 e.hasMoreElements(); ) {
		e.nextElement().cleanupView();
	    }
	}


	freeMessageList.add(univ);
	freeMessageList.add(v);

	evaluateAllCanvases();
	stateWorkThreads.clear();
	renderWorkThreads.clear();
	requestRenderWorkThreads.clear();
	threadListsChanged = true;

	// This notify VirtualUniverse waitForMC() thread to continue
	v.doneUnregister = true;
    }


    /**
     * This procedure create MC thread that start together with MC.
     */
    void createMCThreads() {

	// There is only one renderingAttributesUpdate Thread globally
	createUpdateThread(renderingAttributesStructure);

	// Create timer thread
	java.security.AccessController.doPrivileged(
			    new java.security.PrivilegedAction<Object>() {
              @Override
              public Object run() {
		  synchronized (rootThreadGroup) {
		      timerThread = new TimerThread(rootThreadGroup);
		      timerThread.setPriority(threadPriority);
		  }
		  return null;
	      }
	});
	timerThread.start();

        // Create notification thread
	java.security.AccessController.doPrivileged(
			    new java.security.PrivilegedAction<Object>() {
              @Override
              public Object run() {
		  synchronized (rootThreadGroup) {
		      notificationThread = new NotificationThread(rootThreadGroup);
		      notificationThread.setPriority(threadPriority);
		  }
		  return null;
	      }
	});
	notificationThread.start();
    }

    /**
     * Destroy all VirtualUniverse related threads.
     * This procedure may call two times when Locale detach in a
     * live viewPlatform.
     */
    private void destroyUniverseThreads(VirtualUniverse univ) {

	if (regUniverseList.contains(univ)) {
	    if (J3dDebug.devPhase) {
		J3dDebug.doDebug(J3dDebug.masterControl, J3dDebug.LEVEL_1,
				 "MC: Destroy universe threads " + univ);
	    }
	    destroyUpdateThread(univ.behaviorStructure);
	    destroyUpdateThread(univ.geometryStructure);
	    destroyUpdateThread(univ.soundStructure);
	    destroyUpdateThread(univ.renderingEnvironmentStructure);
	    destroyUpdateThread(univ.transformStructure);
	    univ.behaviorScheduler.finish();
	    univ.behaviorScheduler.free();
	    univ.behaviorScheduler = null;
	    univ.initMCStructure();
	    activeUniverseList.remove(univ);
	    regUniverseList.remove(univ);
	} else {
	    emptyMessageList(univ.behaviorStructure, null);
	    emptyMessageList(univ.geometryStructure, null);
	    emptyMessageList(univ.soundStructure, null);
	    emptyMessageList(univ.renderingEnvironmentStructure, null);
	    emptyMessageList(univ.transformStructure, null);
	}

	if (regUniverseList.isEmpty() && views.isEmpty()) {
	    if(J3dDebug.devPhase) {
		J3dDebug.doDebug(J3dDebug.masterControl, J3dDebug.LEVEL_1,
				 "MC: Destroy RenderingAttributes Update and Timer threads");
	    }
	    if (renderingAttributesStructure.updateThread != null) {
		renderingAttributesStructure.updateThread.finish();
		renderingAttributesStructure.updateThread = null;
	    }
	    renderingAttributesStructure.messageList.clear();
	    renderingAttributesStructure.objList = new ArrayList<J3dMessage>();
	    renderingAttributesStructure = new RenderingAttributesStructure();
	    if (timerThread != null) {
		timerThread.finish();
		timerThread = null;
	    }
            if (notificationThread != null) {
                notificationThread.finish();
                notificationThread = null;
            }

	    // shouldn't all of these be synchronized ???
	    synchronized (VirtualUniverse.mc.deviceScreenMap) {
		deviceScreenMap.clear();
	    }

	    mirrorObjects.clear();
	    // Note: We should not clear the DISPLAYLIST/TEXTURE
	    // list here because other structure may release them
	    // later

	    for(int i=0; i<canvasIds.length; i++) {
		canvasIds[i] = false;
	    }
	    canvasFreeIndex = 0;

	    renderOnceList.clear();
	    timestampUpdateList.clear();

	    defaultRenderMethod = null;
	    text3DRenderMethod = null;
	    vertexArrayRenderMethod = null;
	    displayListRenderMethod = null;
	    compressedGeometryRenderMethod = null;
	    orientedShape3DRenderMethod = null;
	    // Terminate MC thread
	    running = false;
	}
    }

    /**
     * Note that we have to go through all views instead of
     * evaluate only the canvas in a single view since each screen
     * may share by multiple view
     */
    private void evaluateAllCanvases() {

	synchronized (renderThreadData) {
	    // synchronized to prevent lost message when
	    // renderThreadData is clear

	    // First remove all renderrenderThreadData
	    renderThreadData.clear();

	    // Second reset canvasCount to zero
	    View viewArr[] = (View []) views.toArray(false);
	    for (int i=views.size()-1; i>=0; i--) {
		viewArr[i].getCanvasList(true); // force canvas cache update
		Screen3D screens[] = viewArr[i].getScreens();
		for (int j=screens.length-1; j>=0; j--) {
		    screens[j].canvasCount = 0;
		}
	    }


	    // Third create render thread and message thread
	    for (int i=views.size()-1; i>=0; i--) {
		View v = viewArr[i];
		Canvas3D canvasList[][] = v.getCanvasList(false);
		if (!v.active) {
		    continue;
		}

		for (int j=canvasList.length-1; j>=0; j--) {
		    boolean added = false;

		    for (int k=canvasList[j].length-1; k>=0; k--) {
			Canvas3D cv = canvasList[j][k];

			final Screen3D screen  = cv.screen;

			if (cv.active) {
			    if (screen.canvasCount++ == 0) {
				// Create Renderer, one per screen
				if (screen.renderer == null) {
                    	        // get the renderer created for the graphics
			        // device of the screen of the canvas
				// No need to synchronized since only
				// MC use it.
				    Renderer rdr = Screen3D.deviceRendererMap.get(cv.screen.graphicsDevice);
				    if (rdr == null) {
					java.security.AccessController.doPrivileged(
					    new java.security.PrivilegedAction<Object>() {
                                              @Override
                                              public Object run() {

						  synchronized (rootThreadGroup) {
						      screen.renderer
							  = new Renderer(
 							      rootThreadGroup);
						      screen.renderer.setPriority(threadPriority);
						  }
                                                 return null;
                                          }
					});
					screen.renderer.initialize();
					Screen3D.deviceRendererMap.put(screen.graphicsDevice, screen.renderer);
				    } else {
					screen.renderer = rdr;
				    }
				}
			    }
		    	    // offScreen canvases will be handled by the
			    // request renderer, so don't add offScreen canvas
			    // the render list
                            //
                            // Issue 131: Automatic offscreen canvases need to
                            // be added to onscreen list. Special case.
                            //
                            // TODO KCR Issue 131: this should probably be
                            // changed to a list of screens since multiple
                            // off-screen canvases (either auto or manual) can
                            // be used by the same renderer
		            if (!cv.manualRendering) {
				screen.renderer.onScreen = screen;
			    } else {
				screen.renderer.offScreen = screen;
				continue;
			    }

			    if (!added) {
				// Swap message data thread, one per
				// screen only. Note that we don't set
				// lastUpdateTime for this thread so
				// that it won't run in the first round
			        J3dThreadData renderData =
			      	    screen.renderer.getThreadData(v, null);
				renderThreadData.add(renderData);

				// only if renderBin is ready then we
				// update the lastUpdateTime to make it run
				if (v.renderBinReady) {
	    		    	    renderData.lastUpdateTime =
					Math.max(currentTime,
						   renderData.lastUpdateTime);
				}
				added = true;
			    }
			    // Renderer message data thread
			    J3dThreadData renderData =
			      	    screen.renderer.getThreadData(v, cv);
			    renderThreadData.add(renderData);
			    if (v.renderBinReady) {
	    		    	renderData.lastUpdateTime =
					Math.max(currentTime,
						   renderData.lastUpdateTime);
			    }
			}
		    }
		}

	    }
	}

	threadListsChanged = true;
    }

    private void evaluatePhysicalEnv(View v) {
	final PhysicalEnvironment env = v.physicalEnvironment;

	if (env.inputsched == null) {
	    java.security.AccessController.doPrivileged(
		 new java.security.PrivilegedAction<Object>() {
                      @Override
                      public Object run() {
			  synchronized (rootThreadGroup) {
			      env.inputsched = new InputDeviceScheduler(
							rootThreadGroup,
							env);
			      env.inputsched.setPriority(threadPriority);
			  }
			  return null;
		      }
	    });
	    env.inputsched.start();
	    PhysicalEnvironment.physicalEnvMap.put(env, env.inputsched);
	}
	threadListsChanged = true;
    }

    final private void addToStateThreads(J3dThreadData threadData) {
	if (threadData.thread.active) {
	    stateWorkThreads.add(threadData);
	}
    }


    private void assignNewPrimaryView(VirtualUniverse univ) {

	View currentPrimary = univ.getCurrentView();

	if (currentPrimary != null) {
	    currentPrimary.primaryView = false;
	}

	View v[] = (View []) views.toArray(false);
	int nviews = views.size();
	for (int i=0; i<nviews; i++) {
	    View view = v[i];
	    if (view.active && view.isRunning &&
		(univ == view.universe)) {
		view.primaryView = true;
		univ.setCurrentView(view);
		return;
	    }
	}
	univ.setCurrentView(null);
    }


    /**
     * This returns the default RenderMethod
     */
    RenderMethod getDefaultRenderMethod() {
	if (defaultRenderMethod == null) {
	    defaultRenderMethod = new DefaultRenderMethod();
	}
	return defaultRenderMethod;
    }

    /**
     * This returns the text3d RenderMethod
     */
    RenderMethod getText3DRenderMethod() {
	if (text3DRenderMethod == null) {
	    text3DRenderMethod = new Text3DRenderMethod();
	}
	return text3DRenderMethod;
    }


    /**
     * This returns the vertexArray RenderMethod
     */
    RenderMethod getVertexArrayRenderMethod() {
	if (vertexArrayRenderMethod == null) {
	    vertexArrayRenderMethod = new VertexArrayRenderMethod();
	}
	return vertexArrayRenderMethod;
    }

    /**
     * This returns the displayList RenderMethod
     */
    RenderMethod getDisplayListRenderMethod() {
        if (displayListRenderMethod == null) {
            displayListRenderMethod = new DisplayListRenderMethod();
        }
        return displayListRenderMethod;
    }

    /**
     * This returns the compressed geometry RenderMethod
     */
    RenderMethod getCompressedGeometryRenderMethod() {
        if (compressedGeometryRenderMethod == null) {
            compressedGeometryRenderMethod =
		new CompressedGeometryRenderMethod();
        }
        return compressedGeometryRenderMethod;
    }

    /**
     * This returns the oriented shape3d RenderMethod
     */
    RenderMethod getOrientedShape3DRenderMethod() {
	if (orientedShape3DRenderMethod == null) {
	    orientedShape3DRenderMethod = new OrientedShape3DRenderMethod();
	}
	return orientedShape3DRenderMethod;
    }

    /**
     * This notifies MasterControl that the given view has been activated
     */
    private void viewActivate(View v) {

	VirtualUniverse univ = v.universe;

	if (univ == null) {
	    return;
	}

	if (!views.contains(v) || !regUniverseList.contains(univ)) {
	    registerView(v);
	} else if (v.active) {
	    evaluateAllCanvases();
	    return;
	}

	if ((univ.activeViewCount == 0)) {
	    univ.geometryStructure.resetConditionMet();
	    univ.behaviorStructure.resetConditionMet();
	}

	if (v.isRunning) {
	    numActiveViews++;
	    univ.activeViewCount++;
	    renderingAttributesStructure.updateThread.active = true;
	    univ.transformStructure.updateThread.active = true;
	    univ.geometryStructure.updateThread.active = true;
	    univ.soundStructure.updateThread.active = true;
	    univ.renderingEnvironmentStructure.updateThread.active = true;
	}
	univ.behaviorScheduler.active = true;
	univ.behaviorStructure.updateThread.active = true;


	activeUniverseList.addUnique(univ);

	if (v.isRunning) {
	    v.soundScheduler.activate();
	    v.renderBin.updateThread.active = true;
	}
	v.active = true;

	if (v.physicalEnvironment.activeViewRef++ == 0) {
	    v.physicalEnvironment.inputsched.activate();
	}


	if (univ.getCurrentView() == null) {
	    assignNewPrimaryView(univ);
	}

	evaluateAllCanvases();
	v.inRenderThreadData = true;
	threadListsChanged = true;
	// Notify GeometryStructure to query visible atom again
	// We should send message instead of just setting
	// v.vDirtyMask = View.VISIBILITY_POLICY_DIRTY;
	// since RenderBin may not run immediately next time.
	// In this case the dirty flag will lost since
	// updateViewCache() will reset it to 0.
	v.renderBin.reactivateView = true;
    }

    /**
     * Release context associate with view
     */
    private void freeContext(View v) {
	Canvas3D[][] canvasList = v.getCanvasList(false);

	for (int j=canvasList.length-1; j>=0; j--) {
	    for (int k=canvasList[j].length-1; k>=0; k--) {
		Canvas3D cv = canvasList[j][k];
		if (!cv.validCanvas) {
		    if ((cv.screen != null) &&
			(cv.screen.renderer != null)) {
			rendererCleanupArgs[1] = cv;
			rendererCleanupArgs[2] = FREECONTEXT_CLEANUP;
			runMonitor(RUN_RENDERER_CLEANUP, null, null, null,
				   cv.screen.renderer);
			rendererCleanupArgs[1] = null;
		    }
		}
	    }
	}
    }

    /**
     * This notifies MasterControl that the given view has been deactivated
     */
    private void viewDeactivate(View v) {

	if (!views.contains(v) || !v.active) {
	    v.active = false;
	    evaluateAllCanvases();
	    return;
	}

	VirtualUniverse univ = v.universe;

	if (v.isRunning) {
	    // if stopView() invoke before, no need to decrement count
	    --numActiveViews;
	    --univ.activeViewCount;
	}

	if (numActiveViews == 0) {
	    renderingAttributesStructure.updateThread.active = false;
	}

	if (univ.activeViewCount == 0) {
	    // check if destroyUniverseThread invoked before
	    if (univ.behaviorScheduler != null) {
		univ.behaviorScheduler.deactivate();
		univ.transformStructure.updateThread.active = false;
		univ.geometryStructure.updateThread.active = false;
		univ.behaviorStructure.updateThread.active = false;
		univ.soundStructure.updateThread.active = false;
		univ.renderingEnvironmentStructure.updateThread.active
		    = false;
		activeUniverseList.remove(univ);
	    }
	}

	v.soundScheduler.deactivate();
	v.renderBin.updateThread.active = false;
	v.active = false;
	if (--v.physicalEnvironment.activeViewRef == 0) {
	    v.physicalEnvironment.inputsched.deactivate();
	}
	assignNewPrimaryView(univ);


	evaluateAllCanvases();

	freeContext(v);

	v.inRenderThreadData = false;
	threadListsChanged = true;
    }


   /**
     * This notifies MasterControl to start given view
     */
    private void startView(View v) {

	if (!views.contains(v) || v.isRunning || !v.active) {
	    v.isRunning = true;
	    return;
	}

	numActiveViews++;
	renderingAttributesStructure.updateThread.active = true;

	VirtualUniverse univ = v.universe;

	univ.activeViewCount++;
	univ.transformStructure.updateThread.active = true;
	univ.geometryStructure.updateThread.active = true;
	univ.soundStructure.updateThread.active = true;
	univ.renderingEnvironmentStructure.updateThread.active = true;
	v.renderBin.updateThread.active = true;
	v.soundScheduler.activate();
	v.isRunning = true;
	if (univ.getCurrentView() == null) {
	    assignNewPrimaryView(univ);
	}
	threadListsChanged = true;
    }


   /**
     * This notifies MasterControl to stop given view
     */
    private void stopView(View v) {
	if (!views.contains(v) || !v.isRunning || !v.active) {
	    v.isRunning = false;
	    return;
	}

	if (--numActiveViews == 0) {
	    renderingAttributesStructure.updateThread.active = false;
	}
	VirtualUniverse univ = v.universe;

	if (--univ.activeViewCount == 0) {
		univ.transformStructure.updateThread.active = false;
		univ.geometryStructure.updateThread.active = false;
		univ.renderingEnvironmentStructure.updateThread.active = false;
		univ.soundStructure.updateThread.active = false;
	}

	v.renderBin.updateThread.active = false;
	v.soundScheduler.deactivate();
	v.isRunning = false;
	assignNewPrimaryView(univ);
	threadListsChanged = true;
    }

    // Call from user thread
    void addInputDeviceScheduler(InputDeviceScheduler ds) {
	synchronized (inputDeviceThreads) {
	    inputDeviceThreads.add(ds);
	    if (inputDeviceThreads.size() == 1) {
		timerThread.addInputDeviceSchedCond();
	    }
	}
	postRequest(INPUTDEVICE_CHANGE, null);
    }

    // Call from user thread
    void removeInputDeviceScheduler(InputDeviceScheduler ds) {
	inputDeviceThreads.remove(ds);
	postRequest(INPUTDEVICE_CHANGE, null);
    }

    /**
     * Add an object to the mirror object list
     */
    void addMirrorObject(ObjectUpdate o) {
	mirrorObjects.add(o);
    }

    /**
     * This updates any mirror objects.  It is called when threads
     * are done.
     */
    void updateMirrorObjects() {
	ObjectUpdate objs[] = (ObjectUpdate []) mirrorObjects.toArray(false);
	int sz = mirrorObjects.arraySize();

	for (int i = 0; i< sz; i++) {
	    objs[i].updateObject();
	}
	mirrorObjects.clear();
    }


    /**
     * This fun little method does all the hard work of setting up the
     * work thread list.
     */
    private void updateWorkThreads() {

	stateWorkThreads.clear();
	renderWorkThreads.clear();
	requestRenderWorkThreads.clear();

	// First the global rendering attributes structure update
	if (numActiveViews > 0) {
	    addToStateThreads(renderingAttributesStructure.getUpdateThreadData());
	}

	// Next, each of the transform structure updates
	VirtualUniverse universes[] = (VirtualUniverse [])
	                         activeUniverseList.toArray(false);
	VirtualUniverse univ;
	int i;
	int size = activeUniverseList.arraySize();

	for (i=size-1; i>=0; i--) {
	    addToStateThreads(universes[i].transformStructure.getUpdateThreadData());
	}
	lastTransformStructureThread = stateWorkThreads.size();

	// Next, the GeometryStructure, BehaviorStructure,
	//       RenderingEnvironmentStructure, and SoundStructure
	for (i=size-1; i>=0; i--) {
	    univ = universes[i];
	    addToStateThreads(univ.geometryStructure.getUpdateThreadData());
	    addToStateThreads(univ.behaviorStructure.getUpdateThreadData());
	    addToStateThreads(univ.renderingEnvironmentStructure.getUpdateThreadData());
	    addToStateThreads(univ.soundStructure.getUpdateThreadData());
	}

	lastStructureUpdateThread = stateWorkThreads.size();

	// Next, the BehaviorSchedulers
	for (i=size-1; i>=0; i--) {
	    addToStateThreads(universes[i].behaviorScheduler.
			      getThreadData(null, null));
	}


	// Now InputDeviceScheduler

	InputDeviceScheduler ds[] = (InputDeviceScheduler [])
	                              inputDeviceThreads.toArray(true);
	for (i=inputDeviceThreads.size()-1; i >=0; i--) {
	    J3dThreadData threadData = ds[i].getThreadData();
	    threadData.thread.active = true;
	    addToStateThreads(threadData);
	}

	// Now the RenderBins and SoundSchedulers
	View viewArr[] = (View []) views.toArray(false);
	J3dThreadData thread;

	for (i=views.size()-1; i>=0; i--) {
	    View v = viewArr[i];
	    if (v.active && v.isRunning) {
		addToStateThreads(v.renderBin.getUpdateThreadData());
		addToStateThreads(v.soundScheduler.getUpdateThreadData());
	        Canvas3D canvasList[][] = v.getCanvasList(false);
	        int longestScreenList = v.getLongestScreenList();
		Object args[] = null;
		// renderer render
	        for (int j=0; j<longestScreenList; j++) {
	            for (int k=0; k < canvasList.length; k++) {
	                if (j < canvasList[k].length) {
	                    Canvas3D cv = canvasList[k][j];
                            // Issue 131: setup renderer unless manualRendering
			    if (cv.active && cv.isRunningStatus && !cv.manualRendering ) {
				if (cv.screen.renderer == null) {
				    continue;
				}
				thread = cv.screen.renderer.getThreadData(v, cv);
				renderWorkThreads.add(thread);
				args =	(Object []) thread.threadArgs;
				args[0] = RENDER;
				args[1] = cv;
				args[2] = v;
			    }
			}
		    }
		}

		// renderer swap
	        for (int j=0; j<canvasList.length; j++) {
		    for (int k=0; k < canvasList[j].length; k++) {
			Canvas3D cv = canvasList[j][k];
			// create swap thread only if there is at
			// least one active canvas
                        // Issue 131: only if not manualRendering
			if (cv.active && cv.isRunningStatus && !cv.manualRendering) {
			    if (cv.screen.renderer == null) {
				// Should not happen
				continue;
			    }
			    thread = cv.screen.renderer.getThreadData(v, null);
			    renderWorkThreads.add(thread);
			    args = (Object []) thread.threadArgs;
			    args[0] = SWAP;
			    args[1] = v;
			    args[2] = canvasList[j];
			    break;
			}
		    }
		}
	    }
	}

	thread = null;

	for (Enumeration<Renderer> e = Screen3D.deviceRendererMap.elements();
	     e.hasMoreElements(); ) {
	    Renderer rdr = e.nextElement();
	    thread = rdr.getThreadData(null, null);
	    requestRenderWorkThreads.add(thread);
	    thread.threadOpts = J3dThreadData.CONT_THREAD;
	    ((Object[]) thread.threadArgs)[0] = REQUESTRENDER;
	}

	if (thread != null) {
	    thread.threadOpts |= J3dThreadData.WAIT_ALL_THREADS;
	}

	threadListsChanged = false;

	//	 dumpWorkThreads();
    }


    void dumpWorkThreads() {
	System.err.println("-----------------------------");
	System.err.println("MasterControl/dumpWorkThreads");

	J3dThreadData threads[];
	int size = 0;

	for (int k=0; k<3; k++) {
	    switch (k) {
	    case 0:
		threads = (J3dThreadData []) stateWorkThreads.toArray(false);
		size = stateWorkThreads.arraySize();
		break;
	    case 1:
		threads = (J3dThreadData []) renderWorkThreads.toArray(false);
		size = renderWorkThreads.arraySize();
		break;
	    default:
		threads = (J3dThreadData []) requestRenderWorkThreads.toArray(false);
		size = requestRenderWorkThreads.arraySize();
		break;
	    }

	    for (int i=0; i<size; i++) {
		J3dThreadData thread = threads[i];
		System.err.println("Thread " + i + ": " + thread.thread);
		System.err.println("\tOps: " + thread.threadOpts);
		if (thread.threadArgs != null) {
		    Object[] args = (Object[]) thread.threadArgs;
		    System.err.print("\tArgs: ");
		    for (int j=0; j<args.length; j++) {
			System.err.print(args[j] + " ");
		    }
		}
		System.err.println("");
	    }
	}
	System.err.println("-----------------------------");
    }


    /**
     * A convienence wrapper function for various parts of the system
     * to force MC to run.
     */
    final void setWork() {
	runMonitor(SET_WORK, null, null, null, null);
    }

    final void setWorkForRequestRenderer() {
        runMonitor(SET_WORK_FOR_REQUEST_RENDERER, null, null, null, null);
    }

    /**
     * Call from GraphicsConfigTemplate to evaluate current
     * capabilities using Renderer thread to invoke native
     * graphics library functions. This avoid MT-safe problem
     * when using thread directly invoke graphics functions.
     */
    void sendRenderMessage(GraphicsConfiguration gc,
			   Object arg, Integer mtype) {
	Renderer rdr = createRenderer(gc);
	J3dMessage renderMessage = new J3dMessage();
	renderMessage.threads = J3dThread.RENDER_THREAD;
	renderMessage.type = J3dMessage.RENDER_IMMEDIATE;
	renderMessage.universe = null;
	renderMessage.view = null;
	renderMessage.args[0] = null;
	renderMessage.args[1] = arg;
	renderMessage.args[2] = mtype;
	rdr.rendererStructure.addMessage(renderMessage);
	setWorkForRequestRenderer();
    }

    // Issue for Issue 175
    // Pass DestroyCtxAndOffScreenBuffer to the Renderer thread for execution.
    void sendDestroyCtxAndOffScreenBuffer(Canvas3D c) {
        // Assertion check. Look for comment in sendCreateOffScreenBuffer.
        GraphicsDevice gd = c.graphicsConfiguration.getDevice();
	assert Screen3D.deviceRendererMap.get(gd) != null;

	synchronized (mcThreadLock) {
            // Issue 364: create master control thread if needed
	    createMasterControlThread();
            assert mcThread != null;

	    Renderer rdr = createRenderer(c.graphicsConfiguration);
	    J3dMessage createMessage = new J3dMessage();
	    createMessage.threads = J3dThread.RENDER_THREAD;
	    createMessage.type = J3dMessage.DESTROY_CTX_AND_OFFSCREENBUFFER;
	    createMessage.universe = null;
	    createMessage.view = null;
	    createMessage.args[0] = c;
            // Fix for issue 340: send display, drawable & ctx in msg
            createMessage.args[1] = Long.valueOf(0L);
            createMessage.args[2] = c.drawable;
            createMessage.args[3] = c.ctx;
	    rdr.rendererStructure.addMessage(createMessage);
	    synchronized (requestObjList) {
		setWorkForRequestRenderer();
		pendingRequest = true;
	    }
        }
    }

    // Fix for Issue 18
    // Pass CreateOffScreenBuffer to the Renderer thread for execution.
    void sendCreateOffScreenBuffer(Canvas3D c) {
	// Assertion check that the renderer has already been created.
	// If it hasn't, this is very, very bad because it opens up
	// the possibility of an MT race condition since this method
	// can be called from the user's thread, possibly at the same
	// time as the MasterControl thread is trying to create a new
	// Renderer.  Fortunately, this should never happen since both
	// the GraphicsTemplate3D methods that return a valid Graphics
	// Configuration and the Canvas3D constructor will ultimately
	// cause a renderer to be created via sendRenderMessage().
	GraphicsDevice gd = c.graphicsConfiguration.getDevice();
	J3dDebug.doAssert((Screen3D.deviceRendererMap.get(gd) != null),
			  "Screen3D.deviceRendererMap.get(gd) != null");

	synchronized (mcThreadLock) {
            // Create master control thread if needed
	    createMasterControlThread();
            assert mcThread != null;

	    // Fix for Issue 72 : call createRenderer rather than getting
	    // the renderer from the canvas.screen object
	    Renderer rdr = createRenderer(c.graphicsConfiguration);
	    J3dMessage createMessage = new J3dMessage();
	    createMessage.threads = J3dThread.RENDER_THREAD;
	    createMessage.type = J3dMessage.CREATE_OFFSCREENBUFFER;
	    createMessage.universe = null;
	    createMessage.view = null;
	    createMessage.args[0] = c;
	    rdr.rendererStructure.addMessage(createMessage);
	    synchronized (requestObjList) {
		setWorkForRequestRenderer();
		pendingRequest = true;
	    }
	}
    }

    // Issue 347 - Pass AllocateCanvasId to the Renderer thread for execution
    void sendAllocateCanvasId(Canvas3D c) {
        synchronized (mcThreadLock) {
            // Issue 364: create master control thread if needed
            createMasterControlThread();
            assert mcThread != null;

            Renderer rdr = createRenderer(c.graphicsConfiguration);
            J3dMessage createMessage = new J3dMessage();
            createMessage.threads = J3dThread.RENDER_THREAD;
            createMessage.type = J3dMessage.ALLOCATE_CANVASID;
            createMessage.universe = null;
            createMessage.view = null;
            createMessage.args[0] = c;
            rdr.rendererStructure.addMessage(createMessage);
            synchronized (requestObjList) {
                setWorkForRequestRenderer();
                pendingRequest = true;
            }
        }
    }

    // Issue 347 - Pass AllocateCanvasId to the Renderer thread for execution
    void sendFreeCanvasId(Canvas3D c) {
        synchronized (mcThreadLock) {
            // Issue 364: create master control thread if needed
            createMasterControlThread();
            assert mcThread != null;

            Renderer rdr = createRenderer(c.graphicsConfiguration);
            J3dMessage createMessage = new J3dMessage();
            createMessage.threads = J3dThread.RENDER_THREAD;
            createMessage.type = J3dMessage.FREE_CANVASID;
            createMessage.universe = null;
            createMessage.view = null;
            createMessage.args[0] = c;
            rdr.rendererStructure.addMessage(createMessage);
            synchronized (requestObjList) {
                setWorkForRequestRenderer();
                pendingRequest = true;
            }
        }
    }


    /**
     * This is the MasterControl work method for Java 3D
     */
    void doWork() {
	runMonitor(CHECK_FOR_WORK, null, null, null, null);

	synchronized (timeLock) {
	    synchronized (requestObjList) {
		if (pendingRequest) {
		    handlePendingRequest();
		}
	    }
	}

	if (!running) {
	    return;
	}

	if (threadListsChanged) { // Check for new Threads
	    updateWorkThreads();
	}

	synchronized (timeLock) {
	    // This is neccesary to prevent updating
	    // thread.lastUpdateTime from user thread
	    // in sendMessage() or sendRunMessage()
	    updateTimeValues();
	}

	//This is temporary until the view model is updated
	View v[] = (View []) views.toArray(false);
	for (int i=views.size()-1; i>=0; i--) {
	    if (v[i].active) {
		v[i].updateViewCache();
		// update OrientedShape3D
		if ((v[i].viewCache.vcDirtyMask != 0 &&
		     !v[i].renderBin.orientedRAs.isEmpty()) ||
		    (v[i].renderBin.cachedDirtyOrientedRAs != null &&
		     !v[i].renderBin.cachedDirtyOrientedRAs.isEmpty())) {
		    v[i].renderBin.updateOrientedRAs();
		}
	    }
	}

	runMonitor(RUN_THREADS, stateWorkThreads, renderWorkThreads,
		   requestRenderWorkThreads, null);

	if (renderOnceList.size() > 0) {
	    clearRenderOnceList();
	}

	manageMemory();

    }

    private void handlePendingRequest() {

	Object objs[];
	Integer types[];
	int size;
	boolean rendererRun = false;

	objs = requestObjList.toArray(false);
	types = (Integer []) requestTypeList.toArray(false);
	size = requestObjList.size();

	for (int i=0; i < size; i++) {
	    // need to process request in order
	    Integer type = types[i];
	    Object o = objs[i];
           if (type == RESET_CANVAS) {
               Canvas3D cv = (Canvas3D) o;
		if ((cv.screen != null) &&
		    (cv.screen.renderer != null)) {
		    rendererCleanupArgs[1] = o;
		    rendererCleanupArgs[2] = RESETCANVAS_CLEANUP;
		    runMonitor(RUN_RENDERER_CLEANUP, null, null, null,
			       cv.screen.renderer);
		    rendererCleanupArgs[1] = null;
		}
               cv.reset();
	       cv.view = null;
	       cv.computeViewCache();
           }
	   else if (type == ACTIVATE_VIEW) {
		viewActivate((View) o);
	   }
	   else if (type == DEACTIVATE_VIEW) {
		viewDeactivate((View) o);
	    } else if (type == REEVALUATE_CANVAS) {
		evaluateAllCanvases();
	    } else if (type == INPUTDEVICE_CHANGE) {
		inputDeviceThreads.clearMirror();
		threadListsChanged = true;
	    } else if (type == START_VIEW) {
		startView((View) o);
	    } else if (type == STOP_VIEW) {
		View v = (View) o;
		// Collision takes 3 rounds to finish its request
		if (++v.stopViewCount > 4) {
		    v.stopViewCount = -1; // reset counter
		    stopView(v);
		} else {
		    tempViewList.add(v);
		}
	    } else if (type == UNREGISTER_VIEW) {
		unregisterView((View) o);
	    } else if (type == PHYSICAL_ENV_CHANGE) {
		evaluatePhysicalEnv((View) o);
	    } else if (type == EMPTY_UNIVERSE) {
		// Issue 81: We need to process this message as long
		// as there are no views associated with this
		// universe. Previously, this message was ignored if
		// there were views associated with *any* universe,
		// which led to a memory / thread leak.
	        boolean foundView = false;
		VirtualUniverse univ = (VirtualUniverse) o;
		View v[] = (View []) views.toArray(false);
		for (int j = views.size() - 1; j >= 0; j--) {
		    if (v[j].universe == univ) {
			foundView = true;
			break;
		    }
		}
		if (!foundView) {
		    destroyUniverseThreads(univ);
		    threadListsChanged = true;
		}
	    } else if (type == START_RENDERER) {
                if (o instanceof Canvas3D) {
                    Canvas3D c3d = (Canvas3D) o;
                    if (!c3d.isFatalError()) {
                        c3d.isRunningStatus = true;
                    }
                } else {
                    ((Renderer) o).userStop = false;
                }
		threadListsChanged = true;
	    } else if (type == STOP_RENDERER) {
		if (o instanceof Canvas3D) {
		    ((Canvas3D) o).isRunningStatus = false;
		} else {
		    ((Renderer) o).userStop = true;
		}
		threadListsChanged = true;
	    } else if (type == RENDER_ONCE) {
		View v = (View) o;
		// temporary start View for renderonce
		// it will stop afterwards
		startView(v);
		renderOnceList.add(v);
		sendRunMessage(v, J3dThread.UPDATE_RENDER);
		threadListsChanged = true;
		rendererRun = true;
	    } else if (type == FREE_CONTEXT) {
		Canvas3D cv = (Canvas3D ) ((Object []) o)[0];
		if ((cv.screen != null) &&
		    (cv.screen.renderer != null)) {
		    rendererCleanupArgs[1] = o;
		    rendererCleanupArgs[2] = REMOVECTX_CLEANUP;
		    runMonitor(RUN_RENDERER_CLEANUP, null, null, null,
			       cv.screen.renderer);
		    rendererCleanupArgs[1] = null;
		}
		rendererRun = true;
            } else if (type == FREE_DRAWING_SURFACE) {
                Pipeline.getPipeline().freeDrawingSurfaceNative(o);
            } else if (type == GETBESTCONFIG) {
		GraphicsConfiguration gc = ((GraphicsConfiguration [])
			  ((GraphicsConfigTemplate3D) o).testCfg)[0];
		sendRenderMessage(gc, o, type);
		rendererRun = true;
	    } else if (type == ISCONFIGSUPPORT) {
		GraphicsConfiguration  gc = (GraphicsConfiguration)
			  ((GraphicsConfigTemplate3D) o).testCfg;
		sendRenderMessage(gc, o, type);
		rendererRun = true;
	    } else if ((type == SET_GRAPHICSCONFIG_FEATURES) ||
		       (type == SET_QUERYPROPERTIES)) {
		GraphicsConfiguration gc = ((Canvas3D)o).graphicsConfiguration;
		sendRenderMessage(gc, o, type);
		rendererRun = true;
	    } else if (type == SET_VIEW) {
		Canvas3D cv = (Canvas3D) o;
		cv.view = cv.pendingView;
		cv.computeViewCache();
	    }
	}

	// Do it only after all universe/View is register
	for (int i=0; i < size; i++) {
	    Integer type = types[i];
	    if (type == FREE_MESSAGE) {
		if (objs[i] instanceof VirtualUniverse) {
		    VirtualUniverse u = (VirtualUniverse) objs[i];
		    if (!regUniverseList.contains(u)) {
			emptyMessageList(u.behaviorStructure, null);
			emptyMessageList(u.geometryStructure, null);
			emptyMessageList(u.soundStructure, null);
			emptyMessageList(u.renderingEnvironmentStructure, null);
		    }
		} else if (objs[i] instanceof View) {
		    View v = (View) objs[i];
		    if (!views.contains(v)) {
			emptyMessageList(v.soundScheduler, v);
			emptyMessageList(v.renderBin, v);
			if (v.resetUnivCount == v.universeCount) {
			    v.reset();
			    v.universe = null;
			    if (running == false) {
				// MC is about to terminate

				/*
				// Don't free list cause there may
				// have some other thread returning ID
				// after it.
				FreeListManager.clearList(FreeListManager.DISPLAYLIST);
				FreeListManager.clearList(FreeListManager.TEXTURE2D);
				FreeListManager.clearList(FreeListManager.TEXTURE3D);

				synchronized (textureIdLock) {
				    textureIdCount = 0;
				}
				*/
			    }
			}
		    }
		}

	    }

	}
	requestObjList.clear();
	requestTypeList.clear();

	size = tempViewList.size();
	if (size > 0) {
	    if (running) {
		for (int i=0; i < size; i++) {
		    requestTypeList.add(STOP_VIEW);
		    requestObjList.add(tempViewList.get(i));
		}
		setWork();
	    } else { // MC will shutdown
		for (int i=0; i < size; i++) {
		    View v = (View) tempViewList.get(i);
		    v.stopViewCount = -1;
		    v.isRunning = false;
		}
	    }
	    tempViewList.clear();
	    pendingRequest = true;
	} else {
	    pendingRequest = rendererRun || (requestObjList.size() > 0);

	}

	size = freeMessageList.size();
	if (size > 0) {
	    for (int i=0; i < size; i++) {
		requestTypeList.add(FREE_MESSAGE);
		requestObjList.add(freeMessageList.get(i));
	    }
	    pendingRequest = true;
	    freeMessageList.clear();
	}
	if (!running && (renderOnceList.size() > 0)) {
	    clearRenderOnceList();
	}

	if (pendingRequest) {
	    setWork();
	}

	if (rendererRun || requestRenderWorkToDo) {
	    running = true;
	}

    }

    private void clearRenderOnceList() {
	for (int i=renderOnceList.size()-1; i>=0; i--) {
	    View v = (View) renderOnceList.get(i);
	    v.renderOnceFinish = true;
	    // stop after render once
	    stopView(v);
	}
	renderOnceList.clear();
	threadListsChanged = true;

    }

    synchronized void runMonitor(int action,
				 UnorderList stateThreadList,
				 UnorderList renderThreadList,
				 UnorderList requestRenderThreadList,
				 J3dThread nthread) {

        switch (action) {
	case RUN_THREADS:
	    int currentStateThread = 0;
	    int currentRenderThread = 0;
	    int currentRequestRenderThread = 0;
	    View view;
	    boolean done;
	    J3dThreadData thread;
	    J3dThreadData renderThreads[] = (J3dThreadData [])
		                             renderThreadList.toArray(false);
	    J3dThreadData stateThreads[] = (J3dThreadData [])
		                            stateThreadList.toArray(false);
	    J3dThreadData requestRenderThreads[] = (J3dThreadData [])
		                       requestRenderThreadList.toArray(false);
	    int renderThreadSize = renderThreadList.arraySize();
	    int stateThreadSize = stateThreadList.arraySize();
	    int requestRenderThreadSize = requestRenderThreadList.arraySize();

	    done = false;

	    //lock all the needed geometry and image component
	    View[] allView = (View []) views.toArray(false);
	    View currentV;
	    int i;

	    if (lockGeometry)
	    {
		for( i = views.arraySize()-1; i >= 0; i--) {
		    currentV = allView[i];
		    currentV.renderBin.lockGeometry();
		}
	    }

	    while (!done) {
		// First try a RenderThread
		while (!renderWaiting &&
		       currentRenderThread != renderThreadSize) {
		    thread = renderThreads[currentRenderThread++];
		    if (!thread.needsRun) {
			continue;
		    }
		    if ((thread.threadOpts & J3dThreadData.START_TIMER) != 0) {
		        view = (View)((Object[])thread.threadArgs)[2];
		        view.frameNumber++;
		        view.startTime = J3dClock.currentTimeMillis();
		    }


		    renderPending++;

		    if (cpuLimit == 1) {
			thread.thread.args = (Object[])thread.threadArgs;
			thread.thread.doWork(currentTime);
		    } else {
			threadPending++;
			thread.thread.runMonitor(J3dThread.RUN,
						 currentTime,
						 (Object[])thread.threadArgs);
		    }

		    if ((thread.threadOpts & J3dThreadData.STOP_TIMER) != 0) {
			view = (View)((Object[])thread.threadArgs)[3];
			timestampUpdateList.add(view);
		    }

		    if ((thread.threadOpts & J3dThreadData.LAST_STOP_TIMER) != 0) {
			// release lock on locked geometry and image component
			for( i = 0; i < views.arraySize(); i++) {
			    currentV = allView[i];
			    currentV.renderBin.releaseGeometry();
			}
		    }

		    if ((cpuLimit != 1) &&
			(thread.threadOpts &
			 J3dThreadData.WAIT_ALL_THREADS) != 0) {

			renderWaiting = true;
		    }


		    if ((cpuLimit != 1) && (cpuLimit <= threadPending)) {
			state = WAITING_FOR_CPU;
			try {
			    wait();
			} catch (InterruptedException e) {
			    System.err.println(e);
			}
			state = RUNNING;
		    }

		}
		// Now try state threads
		while (!stateWaiting &&
		       currentStateThread != stateThreadSize) {
		    thread = stateThreads[currentStateThread++];

		    if (!thread.needsRun) {
			continue;
		    }

		    statePending++;

		    if (cpuLimit == 1) {
			thread.thread.args = (Object[])thread.threadArgs;
			thread.thread.doWork(currentTime);
		    } else {
			threadPending++;
			thread.thread.runMonitor(J3dThread.RUN,
						 currentTime,
						 (Object[])thread.threadArgs);
		    }
		    if (cpuLimit != 1 && (thread.threadOpts &
			 J3dThreadData.WAIT_ALL_THREADS) != 0) {
			stateWaiting = true;
		    }

		    if ((cpuLimit != 1) && (cpuLimit <= threadPending)) {
			// Fix bug 4686766 - always allow
			// renderer thread to continue if not finish
			// geomLock can release for Behavior thread to
			// continue.
			if (currentRenderThread == renderThreadSize) {
			    state = WAITING_FOR_CPU;
			    try {
				wait();
			    } catch (InterruptedException e) {
				System.err.println(e);
			    }
			    state = RUNNING;
			} else {
			    // Run renderer thread next time
			    break;
			}

		    }
		}

		// Now try requestRender threads
                if (!renderWaiting &&
                     (currentRenderThread == renderThreadSize)) {
                    currentRequestRenderThread = 0;
                    while (!renderWaiting &&
                           (currentRequestRenderThread !=
                                requestRenderThreadSize)) {

                        thread =
			   requestRenderThreads[currentRequestRenderThread++];

                        renderPending++;

                        if (cpuLimit == 1) {
                            thread.thread.args = (Object[])thread.threadArgs;
                            thread.thread.doWork(currentTime);
                        } else {
                            threadPending++;
                            thread.thread.runMonitor(J3dThread.RUN,
                                                currentTime,
                                                (Object[])thread.threadArgs);
                        }
                        if (cpuLimit != 1 && (thread.threadOpts &
                                J3dThreadData.WAIT_ALL_THREADS) != 0) {
                            renderWaiting = true;
                        }
                        if (cpuLimit != 1 && cpuLimit <= threadPending) {
                            state = WAITING_FOR_CPU;
                            try {
                                wait();
                            } catch (InterruptedException e) {
                                System.err.println(e);
                            }
			    state = RUNNING;
                        }
                    }
                }

		if (cpuLimit != 1) {
		    if ((renderWaiting &&
			 (currentStateThread == stateThreadSize)) ||
		          (stateWaiting &&
		            currentRenderThread == renderThreadSize) ||
		    	    (renderWaiting && stateWaiting)) {
			if (!requestRenderWorkToDo) {
		            state = WAITING_FOR_THREADS;
		            try {
			        wait();
		            } catch (InterruptedException e) {
			        System.err.println(e);
		            }
			    state = RUNNING;
			}
			requestRenderWorkToDo = false;
		    }
		}

                if ((currentStateThread == stateThreadSize) &&
                    (currentRenderThread == renderThreadSize) &&
                    (currentRequestRenderThread == requestRenderThreadSize) &&
		    (threadPending == 0)) {
			for (int k = timestampUpdateList.size() - 1; k >= 0; k--) {
				View v = timestampUpdateList.get(k);
				v.setFrameTimingValues();
				v.universe.behaviorStructure.incElapsedFrames();
			}
		    timestampUpdateList.clear();
		    updateMirrorObjects();
		    done = true;

                    if (isStatsLoggable(Level.INFO)) {
                        // Instrumentation of Java 3D renderer
                        logTimes();
                    }
		}
	    }
	    break;

	case THREAD_DONE:
	    if (state != WAITING_FOR_RENDERER_CLEANUP) {

		threadPending--;
                assert threadPending >= 0 : ("threadPending = " + threadPending);
                if (nthread.type == J3dThread.RENDER_THREAD) {
		    View v = (View) nthread.args[3];
		    if (v != null) { // STOP_TIMER
			v.stopTime = J3dClock.currentTimeMillis();
		    }

		    if (--renderPending == 0) {
			renderWaiting = false;
		    }
                    assert renderPending >= 0 : ("renderPending = " + renderPending);
		} else {
		    if (--statePending == 0) {
			stateWaiting = false;
		    }
                    assert statePending >= 0 : ("statePending = " + statePending);
		}
		if (state == WAITING_FOR_CPU || state == WAITING_FOR_THREADS) {
		    notify();
		}
	    } else {
		notify();
		state = RUNNING;
	    }
	    break;

	case CHECK_FOR_WORK:
	    if (!workToDo) {
		state = SLEEPING;
                // NOTE: this could wakeup spuriously (see issue 279), but it
                // will not cause any problems.
		try {
		    wait();
		} catch (InterruptedException e) {
		    System.err.println(e);
		}
	        state = RUNNING;
	    }
	    workToDo = false;
	    break;

	case SET_WORK:
	    workToDo = true;
	    if (state == SLEEPING) {
		notify();
	    }
	    break;

        case SET_WORK_FOR_REQUEST_RENDERER:
	    requestRenderWorkToDo = true;
	    workToDo = true;
	    if (state == WAITING_FOR_CPU || state == WAITING_FOR_THREADS ||
			state == SLEEPING) {
		notify();
	    }
	    break;

	case RUN_RENDERER_CLEANUP:
	    nthread.runMonitor(J3dThread.RUN, currentTime,
			       rendererCleanupArgs);
	    state = WAITING_FOR_RENDERER_CLEANUP;
            // Issue 279 - loop until state is set to running
            while (state != RUNNING) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    System.err.println(e);
                }
            }
	    break;

        default:
            // Should never get here
            assert false : "missing case in switch statement";
        }
    }

    // Static initializer
    static {
        // create ThreadGroup
        java.security.AccessController.doPrivileged(
            new java.security.PrivilegedAction<Object>() {
                @Override
                public Object run() {
                    ThreadGroup parent;
                    Thread thread = Thread.currentThread();
                    threadPriority = thread.getPriority();
                    rootThreadGroup = thread.getThreadGroup();
                    while ((parent = rootThreadGroup.getParent()) != null) {
                        rootThreadGroup = parent;
                    }
                    rootThreadGroup = new ThreadGroup(rootThreadGroup,
                            "Java3D");
                    // use the default maximum group priority
                    return null;
                }
        });

        // Initialize loggers
        try {
            initLoggers();
        } catch (RuntimeException ex) {
            System.err.println(ex);
        }
    }


    static String mtype[] = {
        "INSERT_NODES",
        "REMOVE_NODES",
        "RUN",
        "TRANSFORM_CHANGED",
        "UPDATE_VIEW",
        "STOP_THREAD",
        "COLORINGATTRIBUTES_CHANGED",
        "LINEATTRIBUTES_CHANGED",
        "POINTATTRIBUTES_CHANGED",
        "POLYGONATTRIBUTES_CHANGED",
        "RENDERINGATTRIBUTES_CHANGED",
        "TEXTUREATTRIBUTES_CHANGED",
        "TRANSPARENCYATTRIBUTES_CHANGED",
        "MATERIAL_CHANGED",
        "TEXCOORDGENERATION_CHANGED",
        "TEXTURE_CHANGED",
        "MORPH_CHANGED",
        "GEOMETRY_CHANGED",
        "APPEARANCE_CHANGED",
        "LIGHT_CHANGED",
        "BACKGROUND_CHANGED",
        "CLIP_CHANGED",
        "FOG_CHANGED",
        "BOUNDINGLEAF_CHANGED",
        "SHAPE3D_CHANGED",
        "TEXT3D_TRANSFORM_CHANGED",
        "TEXT3D_DATA_CHANGED",
        "SWITCH_CHANGED",
        "COND_MET",
        "BEHAVIOR_ENABLE",
        "BEHAVIOR_DISABLE",
        "INSERT_RENDERATOMS",
        "ORDERED_GROUP_INSERTED",
        "ORDERED_GROUP_REMOVED",
        "COLLISION_BOUND_CHANGED",
        "REGION_BOUND_CHANGED",
        "MODELCLIP_CHANGED",
        "BOUNDS_AUTO_COMPUTE_CHANGED",
        "SOUND_ATTRIB_CHANGED",
        "AURALATTRIBUTES_CHANGED",
        "SOUNDSCAPE_CHANGED",
        "ALTERNATEAPPEARANCE_CHANGED",
        "RENDER_OFFSCREEN",
        "RENDER_RETAINED",
        "RENDER_IMMEDIATE",
        "SOUND_STATE_CHANGED",
        "ORIENTEDSHAPE3D_CHANGED",
        "TEXTURE_UNIT_STATE_CHANGED",
        "UPDATE_VIEWPLATFORM",
        "BEHAVIOR_ACTIVATE",
        "GEOMETRYARRAY_CHANGED",
        "MEDIA_CONTAINER_CHANGED",
        "RESIZE_CANVAS",
        "TOGGLE_CANVAS",
        "IMAGE_COMPONENT_CHANGED",
        "SCHEDULING_INTERVAL_CHANGED",
        "VIEWSPECIFICGROUP_CHANGED",
        "VIEWSPECIFICGROUP_INIT",
        "VIEWSPECIFICGROUP_CLEAR",
        "ORDERED_GROUP_TABLE_CHANGED",
        "BEHAVIOR_REEVALUATE",
        "CREATE_OFFSCREENBUFFER",
        "DESTROY_CTX_AND_OFFSCREENBUFFER",
        "SHADER_ATTRIBUTE_CHANGED",
        "SHADER_ATTRIBUTE_SET_CHANGED",
        "SHADER_APPEARANCE_CHANGED",
        "ALLOCATE_CANVASID",
        "FREE_CANVASID",
    };

    private String dumpThreads(int threads) {
        StringBuffer strBuf = new StringBuffer();
        strBuf.append("threads:");
	//dump Threads type
        if ((threads & J3dThread.BEHAVIOR_SCHEDULER) != 0) {
            strBuf.append(" BEHAVIOR_SCHEDULER");
        }
        if ((threads & J3dThread.SOUND_SCHEDULER) != 0) {
            strBuf.append(" SOUND_SCHEDULER");
        }
        if ((threads & J3dThread.INPUT_DEVICE_SCHEDULER) != 0) {
            strBuf.append(" INPUT_DEVICE_SCHEDULER");
        }
        if ((threads & J3dThread.RENDER_THREAD) != 0) {
            strBuf.append(" RENDER_THREAD");
        }
        if ((threads & J3dThread.UPDATE_GEOMETRY) != 0) {
            strBuf.append(" UPDATE_GEOMETRY");
        }
        if ((threads & J3dThread.UPDATE_RENDER) != 0) {
            strBuf.append(" UPDATE_RENDER");
        }
        if ((threads & J3dThread.UPDATE_BEHAVIOR) != 0) {
            strBuf.append(" UPDATE_BEHAVIOR");
        }
        if ((threads & J3dThread.UPDATE_SOUND) != 0) {
            strBuf.append(" UPDATE_SOUND");
        }
        if ((threads & J3dThread.UPDATE_RENDERING_ATTRIBUTES) != 0) {
            strBuf.append(" UPDATE_RENDERING_ATTRIBUTES");
        }
        if ((threads & J3dThread.UPDATE_RENDERING_ENVIRONMENT) != 0) {
            strBuf.append(" UPDATE_RENDERING_ENVIRONMENT");
        }
        if ((threads & J3dThread.UPDATE_TRANSFORM) != 0) {
            strBuf.append(" UPDATE_TRANSFORM");
        }

        return strBuf.toString();
    }

    // Method to log the specified message. Note that the caller
    // should check for isCoreLoggable(FINEST) before calling
    private void dumpMessage(String str, J3dMessage m) {
        StringBuffer strBuf = new StringBuffer();
        strBuf.append(str).append(" ");
        if (m.type >= 0 && m.type < mtype.length) {
            strBuf.append(mtype[m.type]);
        } else {
            strBuf.append("<UNKNOWN>");
        }
        strBuf.append("  ").append(dumpThreads(m.threads));
        getCoreLogger().finest(strBuf.toString());
    }


    int frameCount = 0;
    private int frameCountCutoff = 100;

    private void manageMemory() {
	if (++frameCount > frameCountCutoff) {
	    FreeListManager.manageLists();
	    frameCount = 0;
	}
    }

    /**
     * Yields the current thread, by sleeping for a small amount of
     * time.  Unlike <code>Thread.yield()</code>, this method
     * guarantees that the current thread will yield to another thread
     * waiting to run.  It also ensures that the other threads will
     * run for at least a small amount of time before the current
     * thread runs again.
     */
    static final void threadYield() {
	// Note that we can't just use Thread.yield(), since it
	// doesn't guarantee that it will actually yield the thread
	// (and, in fact, it appears to be a no-op under Windows). So
	// we will sleep for 1 msec instead. Since most threads use
	// wait/notify, and only use this when they are waiting for
	// another thread to finish something, this shouldn't be a
	// performance concern.

	//Thread.yield();
	try {
	    Thread.sleep(1);
	}
	catch (InterruptedException e) {
	    // Do nothing, since we really don't care how long (or
	    // even whether) we sleep
	}
    }

    // Return the number of available processors
    private int getNumberOfProcessors() {
        return Runtime.getRuntime().availableProcessors();
    }

    //
    // The following framework supports code instrumentation. To use it,
    // add code of the following form to areas that you want to enable for
    // timing:
    //
    //     long startTime = System.nanoTime();
    //     sortTransformGroups(tSize, tgs);
    //     long deltaTime = System.nanoTime() - startTime;
    //     VirtualUniverse.mc.recordTime(MasterControl.TimeType.XXXXX, deltaTime);
    //
    // where "XXXXX" is the enum representing the code segment being timed.
    // Additional enums can be defined for new subsystems.
    //

    static enum TimeType {
        TOTAL_FRAME,
        RENDER,
        BEHAVIOR,
        // TRANSFORM_UPDATE,
        // ...
    }

    private long[] statTimes = new long[TimeType.values().length];
    private int[] statCounts = new int[TimeType.values().length];
    private boolean[] statSeen = new boolean[TimeType.values().length];
    private int frameCycleTick = 0;
    private long frameCycleNumber = 0L;

    // Method to record times -- should not be called unless the stats logger
    // level is set to INFO or lower
    synchronized void recordTime(TimeType type, long deltaTime) {
        int idx = type.ordinal();
        statTimes[idx] += deltaTime;
        statCounts[idx]++;
        statSeen[idx] = true;
    }

    // Method to record times -- this is not called unless the stats logger
    // level is set to INFO or lower
    private synchronized void logTimes() {
        ++frameCycleNumber;
        if (++frameCycleTick >= 10) {
            StringBuffer strBuf = new StringBuffer();
            strBuf.append("----------------------------------------------\n").
                    append("    Frame Number = ").
                    append(frameCycleNumber).
                    append("\n");
            for (int i = 0; i < statTimes.length; i++) {
                if (statSeen[i]) {
                    strBuf.append("    ");
                    if (statCounts[i] > 0) {
                        strBuf.append(TimeType.values()[i]).
                                append(" [").
                                append(statCounts[i]).
                                append("] = ").
                                append((double)statTimes[i] / 1000000.0 / (double)statCounts[i]).
                                append(" msec per call\n");
                        statTimes[i] = 0L;
                        statCounts[i] = 0;
                    } else {
                        assert statTimes[i] == 0L;
                        strBuf.append(TimeType.values()[i]).
                                append(" [0] = 0.0 msec\n");
                    }
                }
            }
            getStatsLogger().info(strBuf.toString());
            frameCycleTick = 0;
        }
    }

}