File: SoSceneViewer.c++

package info (click to toggle)
inventor 2.1.5-10-21
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 36,312 kB
  • sloc: ansic: 33,864; lisp: 7,361; cpp: 3,874; yacc: 369; sh: 359; perl: 234; awk: 141; makefile: 81; csh: 35; sed: 11
file content (4774 lines) | stat: -rw-r--r-- 145,475 bytes parent folder | download | duplicates (8)
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
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
/*
 *
 *  Copyright (C) 2000 Silicon Graphics, Inc.  All Rights Reserved. 
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library 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
 *  Lesser General Public License for more details.
 *
 *  Further, this software is distributed without any warranty that it is
 *  free of the rightful claim of any third person regarding infringement
 *  or the like.  Any license provided herein, whether implied or
 *  otherwise, applies only to this software file.  Patent licenses, if
 *  any, provided herein do not apply to combinations of this program with
 *  other software, or any other product whatsoever.
 * 
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *  Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
 *  Mountain View, CA  94043, or:
 * 
 *  http://www.sgi.com 
 * 
 *  For further information regarding this notice, see: 
 * 
 *  http://oss.sgi.com/projects/GenInfo/NoticeExplan/
 *
 */

/*
 * Copyright (C) 1990-95   Silicon Graphics, Inc.
 *
 * 
 _______________________________________________________________________
 ______________  S I L I C O N   G R A P H I C S   I N C .  ____________
 |
 |   $Revision: 1.11 $
 |
 |   Classes	: SoSceneViewer
 |
 |   Author(s)	: Thad Beier, David Mott, Alain Dumesny, Paul Isaacs,
 |		  Rikk Carey, Dave Immel
 |
 ______________  S I L I C O N   G R A P H I C S   I N C .  ____________
 _______________________________________________________________________
 */

#include <stdlib.h> // for system() and getenv()
#include <unistd.h> // for access()

#include <X11/StringDefs.h>
#include <X11/Intrinsic.h>
#include <X11/Xatom.h>

#include <Xm/Protocols.h>
#include <Xm/Xm.h>
#include <Xm/BulletinB.h>
#include <Xm/CascadeB.h>
#include <Xm/CascadeBG.h>
#include <Xm/FileSB.h>
#include <Xm/Form.h>
#include <Xm/Label.h>
#include <Xm/FileSB.h>
#include <Xm/PushB.h>
#include <Xm/PushBG.h>
#include <Xm/SeparatoG.h>
#include <Xm/Text.h>
#include <Xm/ToggleB.h>
#include <Xm/ToggleBG.h>
#include <Xm/DropTrans.h>

#include <Inventor/SoDB.h>
#include <Inventor/misc/SoByteStream.h>
#include <Inventor/SoNodeKitPath.h>
#include <Inventor/SoPickedPoint.h>
#include <Inventor/SoLists.h>
#include <Inventor/Xt/SoXt.h>
#include <Inventor/Xt/SoXtClipboard.h>
#include <Inventor/Xt/SoXtDirectionalLightEditor.h>
#include <Inventor/Xt/SoXtMaterialEditor.h>
#include <Inventor/Xt/SoXtPrintDialog.h>
#include <Inventor/Xt/SoXtResource.h>
#include <Inventor/Xt/SoXtTransformSliderSet.h>
#include <Inventor/Xt/viewers/SoXtExaminerViewer.h>
#include <Inventor/Xt/viewers/SoXtFlyViewer.h>
#include <Inventor/Xt/viewers/SoXtPlaneViewer.h>
#include <Inventor/Xt/viewers/SoXtWalkViewer.h>
#include <Inventor/actions/SoBoxHighlightRenderAction.h>
#include <Inventor/actions/SoGetBoundingBoxAction.h>
#include <Inventor/actions/SoGetMatrixAction.h>
#include <Inventor/actions/SoSearchAction.h>
#include <Inventor/actions/SoWriteAction.h>
#include <Inventor/details/SoNodeKitDetail.h>
#include <Inventor/draggers/SoDirectionalLightDragger.h>
#include <Inventor/draggers/SoTabBoxDragger.h>
#include <Inventor/manips/SoCenterballManip.h>
#include <Inventor/manips/SoDirectionalLightManip.h>
#include <Inventor/manips/SoHandleBoxManip.h>
#include <Inventor/manips/SoJackManip.h>
#include <Inventor/manips/SoPointLightManip.h>
#include <Inventor/manips/SoSpotLightManip.h>
#include <Inventor/manips/SoTabBoxManip.h>
#include <Inventor/manips/SoTrackballManip.h>
#include <Inventor/manips/SoTransformBoxManip.h>
#include <Inventor/manips/SoTransformerManip.h>
#include <Inventor/nodekits/SoBaseKit.h>
#include <Inventor/nodekits/SoCameraKit.h>
#include <Inventor/nodekits/SoSceneKit.h>
#include <Inventor/nodes/SoCallback.h>
#include <Inventor/nodes/SoCube.h>
#include <Inventor/nodes/SoDirectionalLight.h>
#include <Inventor/nodes/SoEnvironment.h>
#include <Inventor/nodes/SoLabel.h>
#include <Inventor/nodes/SoLight.h>
#include <Inventor/nodes/SoMaterial.h>
#include <Inventor/nodes/SoOrthographicCamera.h>
#include <Inventor/nodes/SoPointLight.h>
#include <Inventor/nodes/SoSelection.h>
#include <Inventor/nodes/SoShape.h>
#include <Inventor/nodes/SoSpotLight.h>
#include <Inventor/nodes/SoSwitch.h>
#include <Inventor/nodes/SoTranslation.h>

#include "SoSceneViewer.h"
#include "SoSceneMenu.h"
#include "SvManipList.h"
#include "../../samples/widgets/MyColorEditor.h"
#include "../../samples/widgets/MyFileRead.h"
#include "../../samples/widgets/MyDropSite.h"
#include "../../samples/common/InventorLogo.h"

#include <GL/gl.h>
#ifdef DEBUG
#include <assert.h>
#endif
 

//
//  Macros and constants
//

// toggle button macros
#define TOGGLE_ON(BUTTON) \
    XmToggleButtonSetState((Widget) BUTTON, TRUE, FALSE)
#define TOGGLE_OFF(BUTTON) \
    XmToggleButtonSetState((Widget) BUTTON, FALSE, FALSE)

#define	FOG_FUDGE	1.6
#define SV_NUM_LIGHTS	6

#define SWITCH_LIGHT_OFF(SWITCH) (SWITCH)->whichChild.setValue(SO_SWITCH_NONE)
#define SWITCH_LIGHT_ON(SWITCH)  (SWITCH)->whichChild.setValue(SO_SWITCH_ALL)
#define IS_LIGHT_ON(SWITCH)	 ((SWITCH)->whichChild.getValue() == SO_SWITCH_ALL)

#define SV_ENV_LABEL "SoSceneViewer Environment v3.0"

#define _ATOM_(DISPLAY,NAME) (XmInternAtom(DISPLAY, NAME, False))

#define SCREEN(w) XScreenNumberOfScreen(XtScreen(w))

//
//  Structs
//

struct SoSceneViewerData {
    int id;
    SoSceneViewer *classPt;
    Widget widget;
};

class SvLightData {
  public:
    // Constructor inits everything to NULL
    SvLightData();
    
    SoSceneViewer   *classPt;
    SoSwitch	    *lightSwitch;
    SoTranslation   *translation;   // for placing a directional light manip
    SoScale         *scale;
    SoLight	    *light;
    SoScale         *scaleInverse;
    SoTranslation   *translationInverse;
    SoType	    type;
    char	    *name;
    MyColorEditor *colorEditor;
    SbBool     	    isManip();
    SbBool     	    shouldBeManip; // Used to remember what it was when
				   // they all get turned off for writing,
				   // printing, etc.
    Widget	    cascadeWidget;
    Widget	    submenuWidget;
    Widget	    onOffWidget;
    Widget	    iconWidget;
    Widget	    editColorWidget;
    Widget	    removeWidget;
};

SvLightData::SvLightData() 
{
    classPt = NULL;
    lightSwitch = NULL;
    translation = NULL;
    scale = NULL;
    light = NULL;
    scaleInverse = NULL;
    translationInverse = NULL;
    name = NULL;
    colorEditor = NULL;
    shouldBeManip = FALSE;
    cascadeWidget = NULL;
    submenuWidget = NULL;
    onOffWidget = NULL;
    iconWidget = NULL;
    editColorWidget = NULL;
    removeWidget = NULL;
}

SbBool SvLightData::isManip() 
{
    if (light == NULL)
	return FALSE;

    if (light->isOfType( SoDirectionalLightManip::getClassTypeId()))
	return TRUE;
    else if (light->isOfType( SoPointLightManip::getClassTypeId()) )
	return TRUE;
    else if (light->isOfType( SoSpotLightManip::getClassTypeId()) )
	return TRUE;

    return FALSE;
}

////////////////////////////////////////////////////////////////////////
//
//  Set the Inventor logo on the screen.
//
static void
logoCB(void *, SoAction *action)
{
    if (action->isOfType(SoGLRenderAction::getClassTypeId())) {
	glViewport(0, 0, 80, 80);
    }
}

static void
setOverlayLogo(SoXtRenderArea *ra)
{
    static SoSeparator *logo = NULL;
    
    if (logo == NULL) {
	SoInput in;
	in.setBuffer((void *)ivLogo, ivLogoSize);
	logo = SoDB::readAll(&in);
	logo->ref();
	
	// Add a callback node which will set the viewport
	SoCallback *cb = new SoCallback;
	cb->setCallback(logoCB);
	logo->insertChild(cb, 0);
    }
    
    SbColor col(1, 1, 1);
    ra->setOverlayColorMap(1, 1, &col);
    ra->setOverlaySceneGraph(logo);	
}
//
////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////
//
// Public constructor - build the widget right now
//
SoSceneViewer::SoSceneViewer(
    Widget parent,
    const char *name, 
    SbBool buildInsideParent, 
    SoSelection *inputGraph,
    const char *envFile) 
	: SoXtComponent(
	    parent,
	    name, 
	    buildInsideParent) 
//
////////////////////////////////////////////////////////////////////////
{
    // In this case, render area is what the app wants, so buildNow = TRUE
    constructorCommon(inputGraph, envFile, TRUE);
}

////////////////////////////////////////////////////////////////////////
//
// SoEXTENDER constructor - the subclass tells us whether to build or not
//
SoSceneViewer::SoSceneViewer(
    Widget parent,
    const char *name, 
    SbBool buildInsideParent, 
    SoSelection *inputGraph,
    const char *envFile, 
    SbBool buildNow)
	: SoXtComponent(
	    parent,
	    name, 
	    buildInsideParent) 
//
////////////////////////////////////////////////////////////////////////
{
    // In this case, render area may be what the app wants, 
    // or it may want a subclass of render area. Pass along buildNow
    // as it was passed to us.
    constructorCommon(inputGraph, envFile, buildNow);
}

////////////////////////////////////////////////////////////////////////
//
// Called by the constructors
//
// private
//
void
SoSceneViewer::constructorCommon(
    SoSelection *inputGraph,
    const char *envFile, 
    SbBool buildNow)
//
////////////////////////////////////////////////////////////////////////
{
    int	    i;
    
    // getting resources.
    XtGetSubresources(  getParentWidget(), &fileData[0], "intl", "Intl",
                        intl_file_resources, intl_num_file_resources,
			NULL, 0 );
    XtGetSubresources(  getParentWidget(), &editData[0], "intl", "Intl",
                        intl_edit_resources, intl_num_edit_resources,
			NULL, 0 );
    XtGetSubresources(  getParentWidget(), &manipData[0], "intl", "Intl",
                        intl_manip_resources, intl_num_manip_resources,
			NULL, 0 );
    XtGetSubresources(  getParentWidget(), &selData[0], "intl", "Intl",
                        intl_sel_resources, intl_num_sel_resources,
			NULL, 0 );
    XtGetSubresources(  getParentWidget(), &viewData[0], "intl", "Intl",
                        intl_view_resources, intl_num_view_resources,
			NULL, 0 );
    XtGetSubresources(  getParentWidget(), &editorData[0], "intl", "Intl",
                        intl_editor_resources, intl_num_editor_resources,
			NULL, 0 );
    XtGetSubresources(  getParentWidget(), &lightData[0], "intl", "Intl",
                        intl_light_resources, intl_num_light_resources,
			NULL, 0 );
    XtGetSubresources(  getParentWidget(), &Light, "intl", "Intl",
                        intl_lightType_resources, intl_num_lightType_resources,
			NULL, 0 );
    XtGetSubresources(  getParentWidget(), &pulldownData[0], "intl", "Intl",
                        intl_pulldown_resources, intl_num_pulldown_resources,
			NULL, 0 );

    setClassName("SoSceneViewer");
    setSize( SbVec2s(520, 510) );

    // selection is the users scene graph.
    selection  = inputGraph;
    currentViewer = NULL;
    createLightsCameraEnvironment();
    
    // the scene viewer supplies its own camera and lights.
    // in fact, we remove any cameras that might be in the users graph.
    // NOTE: since the camera may be switched by the viewer (ortho/perspective toggle)
    // make sure to get the camera from the viewer (and not cache the camera).
    sceneGraph = new SoSeparator();
    sceneGraph->ref();	// must ref it
    sceneGraph->addChild(lightsCameraEnvironment);
    sceneGraph->addChild(selection);

    // Create the dictionary that keeps track of original camera
    // settings in scenekits
    sceneKitCamNumDict = new SbDict(5);;
#ifndef EXPLORER
    SoCamera *camFromScene = getLastSceneKitCamera(selection);
    switchOffSceneKitCameras(selection);
    removeCameras(selection);
#endif
    
    //
    // Widget and menu variables
    //
    mgrWidget = NULL;
    showMenuFlag = TRUE;
    menuWidget = NULL;
    menuItems = new SoSceneViewerData[SV_MENU_NUM];
    for (i=0; i<SV_MENU_NUM; i++) {
	menuItems[i].id = i;
	menuItems[i].classPt = this;
	menuItems[i].widget = NULL;
    }
    
    //
    // File
    //
    fileName	 = NULL;
    fileDialog	 = NULL;
    printDialog	 = NULL;
    
    //
    // Viewing
    //
    // Allocate only one viewer at a time. The other viewers will
    // be allocated as needed to increase speed and save memory.
    //
    for (i=0; i<4; i++)
	viewerList[i] = NULL;
	
    
    // fog
    fogFlag = FALSE;
    environment->fogType.setValue( SoEnvironment::NONE );    

    antialiasingFlag = FALSE;
    backgroundColorEditor = NULL;

    //
    // Selection
    //     These callbacks are used to update the SceneViewer state after
    //     the current selection changes (e.g. attach/detach editors and manips).
    //
    selection->addSelectionCallback(SoSceneViewer::selectionCallback, this);
    selection->addDeselectionCallback(SoSceneViewer::deselectionCallback, this);
    selection->setPickFilterCallback(SoSceneViewer::pickFilterCB, this);

    highlightRA = new SoBoxHighlightRenderAction;
    
    //
    // Editors
    //
    ignoreCallback = FALSE;
    materialEditor  = NULL;
    colorEditor	    = NULL;
    transformSliderSet = NULL;

    //
    // Manips
    //
    curManip = SV_NONE;
    highlightRA->setVisible(TRUE); // highlight visible when no manip
    curManipReplaces = TRUE;
    maniplist = new SvManipList;
    
#ifdef EXPLORER
    //
    // User callback
    //
    userModeCB = NULL;
    userModedata = NULL;
    userModeFlag = FALSE;
#endif /* EXPLORER */
    
    //
    // Lights
    //
    ambientColorEditor = NULL;
    headlightData = new SvLightData;
    headlightData->classPt = this;
    headlightData->name = Light.headlight;
    headlightData->type = SoDirectionalLight::getClassTypeId();
    headlightData->colorEditor = NULL;
    headlightData->shouldBeManip = FALSE;
    headlightEditor = NULL;
    calculatedLightManipSize = FALSE;
    
    // Build the widget tree, and let SoXtComponent know about our base widget.
    if (buildNow) {
	Widget w = buildWidget(getParentWidget());
	setBaseWidget(w);
    }
    
    // do this after everything else has been set up (viewer needs to exists 
    // because the camera is gotten from the viewer (not cached here))
    if (envFile != NULL)
    	readEnvFile(envFile);

    // If scene had sceneKit with a camera, copy its values into our camera.
    if (camFromScene)
	setCameraFields( camFromScene );
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Destructor.
//
// Use: public

SoSceneViewer::~SoSceneViewer()
//
////////////////////////////////////////////////////////////////////////
{
    // Delete the dictionary that keeps track of original camera
    // settings in scenekits
    delete sceneKitCamNumDict;

    // detach and delete the manips
    detachManipFromAll();
    delete maniplist;

    // detach and delete the viewers
    currentViewer->setSceneGraph(NULL);
    delete (SoXtExaminerViewer *) viewerList[SV_VWR_EXAMINER];
    delete (SoXtFlyViewer *) viewerList[SV_VWR_FLY];
    delete (SoXtWalkViewer *) viewerList[SV_VWR_WALK];
    delete (SoXtPlaneViewer *) viewerList[SV_VWR_PLANE];
    
    // delete menu items data
    delete [ /*SV_MENU_NUM*/ ] menuItems;
    delete headlightData;
    delete headlightEditor;
    
    delete printDialog;
    
    // Editor components
    delete materialEditor;
    delete colorEditor;
    delete transformSliderSet;
    delete ambientColorEditor;
    delete backgroundColorEditor;

    sceneGraph->unref();
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	New data is going to be coming into the viewer.  Time to disconnect all
//  manipulators and picking, and wait for new information.  Might as well go
//  into a viewing mode as well, this gets rid of the manipulators, and puts
//  the user in control of viewing when new data shows up.
//
// Use: public
void
SoSceneViewer::newData()
//
////////////////////////////////////////////////////////////////////////
{
    selection->deselectAll();
}

#ifdef EXPLORER
////////////////////////////////////////////////////////////////////////
//
// Description:
//	This sets the user mode callack routine
//
// Use: public
void 
SoSceneViewer::setUserModeEventCallback(SoXtRenderAreaEventCB *fcn)
//
////////////////////////////////////////////////////////////////////////
{
    userModeCB = fcn;
    userModedata = currentViewer->getSceneGraph();
    if (userModeFlag)
	currentViewer->setEventCallback(userModeCB, userModedata);
}
#endif /* EXPLORER */

////////////////////////////////////////////////////////////////////////
//
// Description:
//	switches from the current viewer to the given viewer. The new
//  viewer will automatically be allocated if needed, and set to have 
//  the same settings the current viewer has (drawing style, buffer 
//  type, etc..).
//
// Use: private
void
SoSceneViewer::switchToViewer(SvEViewer newViewer)
//
////////////////////////////////////////////////////////////////////////
{
    if (whichViewer == newViewer)
    	return;
    
    // remove the sensor + scene graph from the old viewer (to prevent
    // an unecessary redraw of the old viewer)
    currentViewer->setAutoRedraw(FALSE);
    currentViewer->setSceneGraph(NULL);
    
    // allocate the viewer if needed and set the window title.
    // all viewers share the same highlight render action.
    switch (newViewer) {
	case SV_VWR_EXAMINER:
	    // examiner vwr is already created in build()
	    setTitle("SceneViewer (Examiner)");
	    break;
	case SV_VWR_FLY:
	    if ( viewerList[newViewer] == NULL ) {
		viewerList[newViewer] = new SoXtFlyViewer(mgrWidget);
		viewerList[newViewer]->setGLRenderAction(highlightRA);
		viewerList[newViewer]->redrawOnSelectionChange(selection);
	    }
	    setTitle("SceneViewer (Fly)");
	    break;
	case SV_VWR_WALK:
	    if ( viewerList[newViewer] == NULL ) {
		viewerList[newViewer] = new SoXtWalkViewer(mgrWidget);
		viewerList[newViewer]->setGLRenderAction(highlightRA);
		viewerList[newViewer]->redrawOnSelectionChange(selection);
	    }
	    setTitle("SceneViewer (Walk)");
	    break;
	case SV_VWR_PLANE:
	    if ( viewerList[newViewer] == NULL ) {
		viewerList[newViewer] = new SoXtPlaneViewer(mgrWidget);
		viewerList[newViewer]->setGLRenderAction(highlightRA);
		viewerList[newViewer]->redrawOnSelectionChange(selection);
	    }
	    setTitle("SceneViewer (Plane)");
	    break;
    }
    SoXtFullViewer *newVwr = viewerList[newViewer];
    
    // re-init the render action (since it is shared between viewers) now that
    // we are changing windows + set the new scene graph
    newVwr->setAutoRedraw(TRUE);
    newVwr->setSceneGraph(sceneGraph);
    newVwr->getGLRenderAction()->invalidateState();
    
    //
    // make sure the new viewer has all the same settings as 
    // the current viewer. 
    //
    
    // XtRenderArea methods
    //???can't each viewer have it's own background color? especially
    //???if we nuke the background color editor. The user might set the
    //???colors to be different in the app-defaults file.
    //???newVwr->setBackgroundColor( currentViewer->getBackgroundColor() );
    
    environment->fogColor.setValue( newVwr->getBackgroundColor() );
    
    newVwr->setClearBeforeRender( currentViewer->isClearBeforeRender() );
    // XtViewer methods
    newVwr->setHeadlight( currentViewer->isHeadlight() );
    newVwr->setDrawStyle( 
		SoXtViewer::STILL,
		currentViewer->getDrawStyle(SoXtViewer::STILL) );
    newVwr->setDrawStyle( 
		SoXtViewer::INTERACTIVE,
		currentViewer->getDrawStyle(SoXtViewer::INTERACTIVE) );
    newVwr->setBufferingType( currentViewer->getBufferingType() );
    newVwr->setViewing( currentViewer->isViewing() );
    newVwr->setAutoClipping( currentViewer->isAutoClipping() );
    newVwr->setSeekTime( currentViewer->getSeekTime() );
    // XtFullViewer methods
    newVwr->setDecoration( currentViewer->isDecoration() );

    // The tabBoxManip adds a finish callback to the viewer.
    // We need to remove from the old and add to the new.
    for (int m = 0; m < maniplist->getLength(); m++ ) {
	SoTransformManip *manip = maniplist->getManip(m);	
	if ( manip->isOfType( SoTabBoxManip::getClassTypeId() ) ) {

	    currentViewer->removeFinishCallback( 
		&SoSceneViewer::adjustScaleTabSizeCB, manip->getDragger() );
	    newVwr->addFinishCallback( 
	        &SoSceneViewer::adjustScaleTabSizeCB, manip->getDragger() );
	}
    }
    
#ifdef EXPLORER
    if (userModeFlag)
	newVwr->setEventCallback(userModeCB, userModedata);
    else
	newVwr->setEventCallback(NULL, NULL);
#endif
    
    // build and layout the new viewer
    buildAndLayoutViewer(newVwr);
    
    // finally switch to the new viewer by showing the new viewer, 
    // and hidding the old viewer (hide is done last to reduce flicker).
    newVwr->show();
    currentViewer->hide();
    whichViewer = newViewer;
    currentViewer = newVwr;
    setOverlayLogo(currentViewer);
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Move up the picked path to the parent group.
//
// Use: public

void
SoSceneViewer::pickParent()
//
////////////////////////////////////////////////////////////////////////
{
    SoFullPath  *pickPath;
    int	    	parentIndex;

    // We'll pick the parent of the last selection in the list...
    pickPath = (SoFullPath *) (*selection)[selection->getNumSelected() - 1];	
    if(pickPath == NULL || pickPath->getLength() < 2)
	return;

    // Get actual node that is the current selection:
    SoNode *tail     = pickPath->getTail();
    SoNode *kitTail  = ((SoNodeKitPath *)pickPath)->getTail();
    SoType nkt = SoBaseKit::getClassTypeId();
    if ( kitTail->isOfType( nkt ) )
	tail = kitTail;
    else
	kitTail = NULL;

    // If kitTail is at top of path, we've already gone as high as we can go.
    if ( kitTail == pickPath->getHead() )
	return;

    // Get index of parent of selection.
    if ( kitTail != NULL ) {
        // Look for first kit above tail. If none, use direct parent of kitTail.
	SoNode *aboveTail = ((SoNodeKitPath *)pickPath)->getNodeFromTail( 1 );
	SbBool aboveIsKit = aboveTail->isOfType( nkt );
	for (int i = pickPath->getLength() - 1; i >= 0; i-- ) {
	    if ( aboveIsKit ) {
		if (pickPath->getNode(i) == aboveTail ) {
		    parentIndex = i;
		    break;
		}
	    }
	    else if ( pickPath->getNode(i) == kitTail ) {
		parentIndex = i - 1;
		break;
	    }
	}
    }
    else {
	// If tail is not a nodkeit, parentIndex is just parent of tail...
	parentIndex = pickPath->getLength() - 2;
    }
    
    // cannot select the selection node (make sure we're not)
    if (pickPath->getNode(parentIndex) == selection) {
    	fprintf(stderr, "No more parents to pick (cannot pick above the selection node)\n");
    	return;
    }
	
    pickPath->ref();				// need to ref it, because
						// selection->clear unref's it
    selection->deselectAll();
    pickPath->truncate(parentIndex + 1);		// Make path end at parentIndex
    selection->select(pickPath);		// add path back in
    pickPath->unref();				// now we can unref it, again
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Pick all group nodes and shapes under selection.
//
// Use: private
void
SoSceneViewer::pickAll()
//
////////////////////////////////////////////////////////////////////////
{
    selection->deselectAll();

#ifdef DEBUG
    assert(selection != NULL);
#endif

    SoPathList myPaths;

    // Our callbacks on the selection's 'select' method may add 
    // more children to the selection node (by making a trackball or handlebox)
    // Therefore, we must first determine the selections by storing
    // paths to them.
    // Following this, we call 'select' on each path, in turn.

    //
    // Create paths from the selection node to all of it's children
    // that are groups or shapes.
    //
    for (int i = 0; i < selection->getNumChildren(); i++) {
    	SoNode *node = selection->getChild(i);
	if ((node->isOfType(SoGroup::getClassTypeId()) ||
	     node->isOfType(SoShape::getClassTypeId())) )
	{
	    SoPath *thisPath = new SoPath(selection);
	    thisPath->append(i);

	    myPaths.append( thisPath );
	}
    }

    //
    // Select each path in 'myPaths'
    //
    for (int j = 0; j < myPaths.getLength(); j++)
	selection->select(myPaths[j]);
}


////////////////////////////////////////////////////////////////////////
//
// Description:
//	This routine first detaches manipulators from all selected objects,
//      then attaches a manipulator to all selected objects.
//
// Use: private

void
SoSceneViewer::replaceAllManips( 
	SvEManipMode manipMode )		// Current manipulator
//
////////////////////////////////////////////////////////////////////////
{
    detachManipFromAll();
    attachManipToAll( manipMode );
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	This routine attaches a manipulator to all selected objects.
//
// Use: private

void
SoSceneViewer::attachManipToAll( 
	SvEManipMode manipMode )		// Current manipulator
//
////////////////////////////////////////////////////////////////////////
{
    int	    i;

    for ( i = 0; i < selection->getNumSelected(); i++ ) {
	SoPath *p = (*selection)[i];
	attachManip( manipMode, p );
    }
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	This routine attaches and activates a manipulator.  
//
// Use: private

void
SoSceneViewer::attachManip( 
	SvEManipMode manipMode,		// Current manipulator
	SoPath *selectedPath )	// Which selection to attach to
//
////////////////////////////////////////////////////////////////////////
{
    SoTransformManip 	*theXfManip;
    SoPath		*xfPath;

    //
    // Attach to a manipulator.
    //

    if ( manipMode == SV_NONE )
	return;

    xfPath = findTransformForAttach( selectedPath );
    xfPath->ref();
    theXfManip = NULL;

    switch( manipMode ) {
      case SV_TRANSFORMER:
	theXfManip = new SoTransformerManip;
	break;

      case SV_TRACKBALL:
	theXfManip = new SoTrackballManip;
	break;

      case SV_HANDLEBOX:
	theXfManip = new SoHandleBoxManip;

  	break;

      case SV_JACK:
	theXfManip = new SoJackManip;
  	break;

      case SV_CENTERBALL:
	theXfManip = new SoCenterballManip;
  	break;

      case SV_XFBOX:
	theXfManip = new SoTransformBoxManip;
  	break;

      case SV_TABBOX:
	theXfManip = new SoTabBoxManip;
  	break;

      case SV_NONE:
	return;
    }

    if ( theXfManip ) {

	SoFullPath *fp = (SoFullPath *) xfPath;

#ifdef DEBUG
	if ( !fp->getTail()->isOfType( SoTransform::getClassTypeId() ) ) {
	    fprintf(stderr,"DBG> Fatal Error: in SoSceneViewer::attachManip\n");
	    fprintf(stderr,"   > end of path is not a transform\n");
	}
#endif
	SoTransform *oldXf = (SoTransform *)fp->getTail();
	oldXf->ref();
	theXfManip->ref();

	if ( !theXfManip->replaceNode( xfPath ) ) {
	    theXfManip->unref();
#ifdef DEBUG
	    fprintf(stderr,"DBG> Fatal Error: in SoSceneViewer::attachManip\n");
	    fprintf(stderr,"   > manip->replaceNode() failed!\n" );
#endif
	}

	// If the transformSliderSet is attached to the oldXf, then attach 
	// it to the new manip instead.
	if ( transformSliderSet && transformSliderSet->isVisible()
	     && transformSliderSet->getNode() == oldXf)
		transformSliderSet->setNode(theXfManip);

	// Add manip and paths to the maniplist (maniplist will ref/unref)
	maniplist->append(selectedPath, theXfManip, xfPath );

	theXfManip->unref();
	oldXf->unref();

	if ( manipMode == SV_TABBOX ) {
	    // Special case!  When using a  tab box, we want to adjust the
	    // scale tabs upon viewer finish.
	    currentViewer->addFinishCallback( 
	       &SoSceneViewer::adjustScaleTabSizeCB,theXfManip->getDragger());
	}
	if ( manipMode == SV_JACK ) {
	    // Special case! For jack manip, we want it so that clicking on the
	    // selected object initiates 2-dimensional translation.  Other
	    // parts of the jack manip should use the default resource geometry.
	    // So, we replace the parts that do planar motion. 
	    // We need to replace a total of six parts:
	    //     'translator.yzTranslator.translator':
	    //     'translator.xzTranslator.translator': 
	    //     'translator.xyTranslator.translator': 
	    //     'translator.yzTranslator.translatorActive': 
	    //     'translator.xzTranslator.translatorActive': 
	    //     'translator.xyTranslator.translatorActive': 
	    // In the SoJackDragger, 'translator' is an SoDragPointDragger, 
	    // which takes care of all translations in 3 dimensions for jack.
	    // In the SoDragPointDragger there are 3 planar translation parts 
	    // (each is an SoTranslate2Dragger) and 3 linear translation parts 
	    // (each is an SoTranslate1Dragger).  At any given time, dragPoint
	    // displays one of each kind of dragger. We leave the linear 
	    // translators as the default geometry (a cylinder along the axis 
	    // of motion), but replace the geometry in the planar translators.
	    // Within the SoDragPointDragger, the planar translators are named
	    // 'yzTranslator', 'xzTranslator', and 'xyTranslator'.  
	    // Each of these is an SoTranslate2Dragger, which has two parts
	    // for its geometry, 'translator' and 'translatorActive.' Clicking
	    // on the 'translator' is what initiates the 2D translation.
	    // Once begun, the 'translatorActive' part is displayed. We
	    // replace both of these parts with a path to the selected object.

	    // When we call setPartAsPath, we need to prune the path if our
	    // selected geometry lays inside a nodekit.
	    // For example, let's say a dumbBellKit contains 1 bar (a cylinder)
	    // and 2 end (spheres).  Since this is the lowest-level kit 
	    // containing these 3 shapes, they are considered a single object
	    // by the SceneViewer.
	    // So we need to pass a path to the kit, not the individual piece
	    // that is selected.  This way, subsequent clicks on any piece of 
	    // the dumbbell will cause 2D translation.
		// First, is a nodekit on the path? If so, find the last one.
		SoFullPath *jackP = (SoFullPath *) selectedPath;
		SoType     bkType = SoBaseKit::getClassTypeId();
		int        lastKitInd = -1;
		for (int i = jackP->getLength() - 1; i >= 0; i--) {
		    if (jackP->getNode(i)->isOfType(bkType)) {
			lastKitInd = i;
			break;
		    }
		}
		// If there's a lastKitInd, make jackP be a copy of 
		// selectedPath, but only up to lastKitInd.
		if ( lastKitInd != -1)
		    jackP = (SoFullPath *) selectedPath->copy(0,lastKitInd + 1);

	    // Get the dragger from the manip (the manip contains the dragger,
	    // and the dragger has the parts).
		SoDragger *d = theXfManip->getDragger();

	    // Use jackP to set the translator parts, then discard (unref) it:
		jackP->ref();
		d->setPartAsPath("translator.yzTranslator.translator", jackP );
		d->setPartAsPath("translator.xzTranslator.translator", jackP );
		d->setPartAsPath("translator.xyTranslator.translator", jackP );
		d->setPartAsPath(
			    "translator.yzTranslator.translatorActive", jackP);
		d->setPartAsPath(
			    "translator.xzTranslator.translatorActive", jackP);
		d->setPartAsPath(
			    "translator.xyTranslator.translatorActive", jackP);
		jackP->unref();
	}
    }

    xfPath->unref();
}


////////////////////////////////////////////////////////////////////////
//
// Description:
//	This routine detaches the manipulators from all selected objects.
//
// Use: private
void
SoSceneViewer::detachManipFromAll() 
//
////////////////////////////////////////////////////////////////////////
{
    //
    // Loop from the end of the list to the start.
    //
    for (int i = selection->getNumSelected() - 1; i >= 0 ; i-- ) {
	SoPath *p = (SoPath *) (*selection)[i];
	detachManip( p );
    }
}


////////////////////////////////////////////////////////////////////////
//
// Description:
//	This routine detaches a manipulator.  
//
// Use: private

void
SoSceneViewer::detachManip(
	SoPath *p )		// Selection object that is being removed
//
////////////////////////////////////////////////////////////////////////
{
    //
    // Detach manip and remove from scene graph.
    //
    int which = maniplist->find(p);
    // See if this path is registered in the manip list.
    if (which != -1) {
	// remove from scene graph
	SoTransformManip *manip = maniplist->getManip(which);

	if ( manip->isOfType(SoTabBoxManip::getClassTypeId() )) {
	    // Special case!  When using a  tab box, we want to adjust the
	    // scale tabs upon viewer finish.
	    currentViewer->removeFinishCallback( 
		&SoSceneViewer::adjustScaleTabSizeCB, manip->getDragger() );
	}

	SoPath *xfPath = maniplist->getXfPath(which);
	SoTransform *newXf = new SoTransform;
	newXf->ref();
	manip->ref();

	// replace the manip
	manip->replaceManip( xfPath, newXf );

	// If the transformSliderSet is attached to the manip, then attach 
	// it to the new node instead.
	if ( transformSliderSet && transformSliderSet->isVisible()
	     && transformSliderSet->getNode() == manip)
		transformSliderSet->setNode(newXf);

	manip->unref();
	newXf->unref();
	
	// remove from maniplist
	maniplist->remove(which);
    }
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Added as a finish callback to the current viewer. It makes sure
//      the scale tab size gets changed when a viewer gesture is 
//      completed.
//
// Use: public
void
SoSceneViewer::adjustScaleTabSizeCB( void *userData, SoXtViewer *)
//
////////////////////////////////////////////////////////////////////////
{
    SoTabBoxDragger *dragger = (SoTabBoxDragger *) userData;
    dragger->adjustScaleTabSize();
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	See the selection from the camera
//
// Use: public
void
SoSceneViewer::viewSelection()
//
////////////////////////////////////////////////////////////////////////
{
    if (selection->getNumSelected() == 0) {
	viewAll();
	return;
    }
    
    SoPath *path = (*selection)[0];
    if(path != NULL) {
	getCamera()->viewAll(path, currentViewer->getViewportRegion());
    }
    else {
	viewAll();
	return;
    }
}


////////////////////////////////////////////////////////////////////////
//
// Description:
//	Create a color editor for the currently selected object.
//      Attachment code copied from SoXformManip.c++
//
// Use: private
void
SoSceneViewer::createColorEditor()
//
////////////////////////////////////////////////////////////////////////
{
    if (colorEditor == NULL) {
	colorEditor = new MyColorEditor;
	colorEditor->setWYSIWYG(TRUE);
	colorEditor->setTitle("Diffuse Color");
    }

    SoMaterial *editMaterial = findMaterialForAttach( NULL );
    
    colorEditor->attach(&(editMaterial->diffuseColor), 0, editMaterial);

    colorEditor->show();
}


////////////////////////////////////////////////////////////////////////
//
// Description:
//   Find the appropriate material node in the scene graph to attach a material
//   editor to.
//
//   Two possible cases:
//        [1] The path-tail is NOT a group.  We search the siblings of the path
//            tail (including the tail itself) from right to left for a node
//	      that is affected by materials (shapes or groups).
//            We stop the search if we come to a material node to the left of the
//	      pathTail.  If we find a node that IS affected by material, we will
//	      insert a material node just before the path-tail. This is
//            because the editor should not affect nodes that appear
//            before attachPath in the scene graph.
//        [2] The path-tail IS a group.  We search the children from left to
//            right for material nodes.
//            We stop the search if we come to a material node.
//            If we find a node that is affected by materials, we will insert a
//	      material just before this node. This is because the editor for a
//	      group should affect ALL nodes within that group.
//
// NOTE: For the purposes of this routine, we consider SoSwitch as different
//       from other types of group. This is because we don't want to put
//       the new node underneath the switch, but next to it.
//
// Use: private
//
SoMaterial *
SoSceneViewer::findMaterialForAttach(
			const SoPath *target )	// path to start search from
//
////////////////////////////////////////////////////////////////////////
{
    int 		pathLength;
    SoPath 		*selectionPath;
    SoMaterial		*editMtl;

    SbBool		madeNewMtl = FALSE; // did we create a new material
					    // node within this method?


    if ( ( selectionPath = (SoPath *) target ) == NULL ) {
	//
	//  If no selection path is specified, then use the LAST path in the
	//  current selection list.
	//
	selectionPath = (*selection)[selection->getNumSelected() - 1];	// last guy
    }
    pathLength = selectionPath->getLength();

    if ( pathLength <= 0 ) {
	fprintf( stderr, "No objects currently selected...\n" );
	return NULL;
    }

#ifdef DEBUG
    if ( pathLength < 2 ) {
	fprintf( stderr, "Picked object has no parent...\n" );
	return NULL;
    }
#endif


    // find 'group' and try to find 'editMtl'
    SoGroup     *group;
    SoNode      *node;
    int         index, i;
    SbBool	ignoreNodekit = FALSE;

    editMtl = NULL;

    if ( selectionPath->getTail()->isOfType( SoBaseKit::getClassTypeId() )) {
	// Nodekits have their own built in policy for creating new material
	// nodes. Allow them to contruct and return it.
	// Get the last nodekit in the path:
	SoBaseKit *kit = (SoBaseKit *) 
			 ((SoNodeKitPath *)selectionPath)->getTail();
	// SO_CHECK_PART returns NULL if the part doesn't exist yet...
	editMtl = SO_GET_PART( kit, "material", SoMaterial );
	if ( editMtl == NULL ) {
	    // This nodekit does not have a material part.
	    // Ignore the fact that this is a nodekit.
	    ignoreNodekit = TRUE;
	}
    }

    SbBool isTailGroup 	= 
      selectionPath->getTail()->isOfType( SoGroup::getClassTypeId()) &&
      (!selectionPath->getTail()->isOfType( SoSwitch::getClassTypeId()));
    
    if ((editMtl == NULL) && ( !isTailGroup )) {
	//
        //    CASE 1: The path-tail is not a group.
        //    'group'      becomes the second to last node in the path.
        //    We search the path tail and its siblings from right to left for a
        //    mtl node.
        //    We stop the search if we come to a shape node or a group node
        //    to the left of the pathTail.  If we find a shape or group, we
        //    will insert a mtl just before the path-tail. This is
        //    because the manipulator should not affect objects that appear
        //    before selectionPath in the scene graph.
	//
        group      = (SoGroup *) selectionPath->getNode(pathLength - 2);
        index      = group->findChild( selectionPath->getTail() );

        for (i = index; (i >= 0) && (editMtl == NULL); i--){
            node = group->getChild(i);
            if (node->isOfType(SoMaterial::getClassTypeId())) // found SoMaterial
                editMtl = (SoMaterial *) node;
            else if ( i != index ) { 
                if ( isAffectedByMaterial( node ) )
                    break;
            }
        }

        if ( editMtl == NULL ) {
            editMtl = new SoMaterial;
            group->insertChild( editMtl, index );
	    madeNewMtl = TRUE;
        }
    }
    else if (editMtl == NULL) {
        //    CASE 2: The path-tail is a group.
        //    'group'      becomes the path tail
        //      We search the children from left to right for mtl nodes.
        //      We stop the search if we come to a shape node or a group node.
        //      If we find a shape or group, we will insert a mtl just
        //      before this shape or group. This is because the editor
        //      for a group should affect ALL objects within that group.
	//
        group = (SoGroup *) selectionPath->getTail();
        for (i = 0; (i < group->getNumChildren()) && (editMtl == NULL); i++ ) {
            node = group->getChild(i);
            if (node->isOfType(SoMaterial::getClassTypeId()))
                editMtl = (SoMaterial *) node;
            else if ( isAffectedByMaterial( node ) )
                break;
        }

        if ( editMtl == NULL ) {
            editMtl = new SoMaterial;
            group->insertChild( editMtl, i );
	    madeNewMtl = TRUE;
        }
    }

    // If we just created the material node here, then set the ignore
    // flags for all fields in the node.  This will cause the fields
    // to be inherited from their ancestors. The material editor will
    // undo these flags whenever it changes the value of a field
    if ( madeNewMtl == TRUE ) {
	editMtl->ambientColor.setIgnored( TRUE );
	editMtl->diffuseColor.setIgnored( TRUE );
	editMtl->specularColor.setIgnored( TRUE );
	editMtl->emissiveColor.setIgnored( TRUE );
	editMtl->shininess.setIgnored( TRUE );
	editMtl->transparency.setIgnored( TRUE );
    }

    // If any of the fields is ignored, then fill the value with the value
    // inherited from the rest of the scene graph
    if ( editMtl->ambientColor.isIgnored() 
	|| editMtl->diffuseColor.isIgnored() 
	|| editMtl->specularColor.isIgnored() 
	|| editMtl->emissiveColor.isIgnored() 
	|| editMtl->shininess.isIgnored() 
	|| editMtl->transparency.isIgnored() ){

	// Create a path to the material
	SoPath *mtlPath;
	if ( (! ignoreNodekit) && selectionPath->getTail()->isOfType( SoBaseKit::getClassTypeId() )) {
	    SoBaseKit *kit = (SoBaseKit *) 
			     ((SoNodeKitPath *)selectionPath)->getTail();
	    mtlPath = kit->createPathToPart( "material", TRUE, selectionPath );
	    mtlPath->ref();
	}
	else {
	    if ( !isTailGroup ) {
		// CASE 1: path-tail was NOT 'group' -- copy all but last entry
		mtlPath = selectionPath->copy(0, pathLength - 1);
	    }
	    else {
		// CASE 2: path-tail was 'group' -- copy all of editPath
		mtlPath = selectionPath->copy(0, pathLength);
	    }
	    mtlPath->ref();
	    // add the material to the end of the path
	    int mtlIndex    = group->findChild(editMtl);
	    mtlPath->append( mtlIndex );
	}

	// Pass the material node to an accumulate state callback
	// that will load any 'ignored' values with their inherited values.
	SoCallbackAction cba;
	cba.addPreTailCallback( SoSceneViewer::findMtlPreTailCB, editMtl);
	cba.apply( mtlPath );

	mtlPath->unref();
    }


    return( editMtl );
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//   Callback used by 'findMaterialForAttach' as part of the accumulate state
//   action. Returns 'PRUNE', which tells the action not to draw the
//   shape as part of the accum state action.
//   editor to.
//
// Use: private
//
SoCallbackAction::Response
SoSceneViewer::findMtlPreTailCB( void *data, SoCallbackAction *accum, 
				 const SoNode * )
//
////////////////////////////////////////////////////////////////////////
{
    SoMaterial *mtl = (SoMaterial *) data;

    SbColor ambient, diffuse, specular, emissive;
    float   shininess, transparency;

    accum->getMaterial( ambient, diffuse, specular, emissive, 
			shininess, transparency ); 

    // inherit the accumulated values only in those fields being ignored.
    if ( mtl->ambientColor.isIgnored() )
	 mtl->ambientColor.setValue( ambient );
    if ( mtl->diffuseColor.isIgnored() )
	 mtl->diffuseColor.setValue( diffuse );
    if ( mtl->specularColor.isIgnored() )
	 mtl->specularColor.setValue( specular );
    if ( mtl->emissiveColor.isIgnored() )
	 mtl->emissiveColor.setValue( emissive );
    if ( mtl->shininess.isIgnored() )
	 mtl->shininess.setValue( shininess );
    if ( mtl->transparency.isIgnored() )
	 mtl->transparency.setValue( transparency );

    return SoCallbackAction::ABORT;
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//   Find the appropriate transform node in the scene graph for attaching a 
//   transform editor or manipulator.
//
//   How we treat the 'center' field of the transform node:
//   If we need to create a new transform node:
//       set the 'center' to be the geometric center of all objects 
//       affected by that transform. 
//   If we find a transform node that already exists:
//       'center' will not be changed.
//
//   Three possible cases:
//        [1] The path-tail is a node kit. Just ask the node kit for a path
//            to the part called "transform"
//        [2] The path-tail is NOT a group.  We search the siblings of the path
//            tail (including the tail itself) from right to left for a node
//	      that is affected by transforms (shapes, groups, lights,cameras).
//            We stop the search if we come to a transform node to the left of 
//	      the pathTail.  If we find a node that IS affected by transform, 
//	      we will insert a transform node just before the path-tail. This is
//            because the editor should not affect nodes that appear
//            before attachPath in the scene graph.
//        [3] The path-tail IS a group.  We search the children from left to
//            right for transform nodes.
//            We stop the search if we come to a transform node.
//            If we find a node that is affected by transform, we will insert a
//	      transform just before this node. This is because the editor for a
//	      group should affect ALL nodes within that group.
//
// NOTE: For the purposes of this routine, we consider SoSwitch as different
//       from other types of group. This is because we don't want to put
//       the new node underneath the switch, but next to it.
//
// Use: private
//
SoPath *
SoSceneViewer::findTransformForAttach(
			const SoPath *target )	// path to start search from
//
////////////////////////////////////////////////////////////////////////
{
    int 		pathLength;
    SoPath 		*selectionPath;
    SoTransform		*editXform;

    
    if ( ( selectionPath = (SoPath *) target ) == NULL ) {
	//
	//  If no selection path is specified, then use the LAST path in the
	//  current selection list.
	//
	selectionPath = (*selection)[selection->getNumSelected() - 1];
    }
    pathLength = selectionPath->getLength();

    if ( pathLength <= 0 ) {
	fprintf( stderr, "No objects currently selected...\n" );
	return NULL;
    }

#ifdef DEBUG
    if ( pathLength < 2 ) {
	fprintf( stderr, "Picked object has no parent...\n" );
	return NULL;
    }
#endif

    // find 'group' and try to find 'editXform'
    SoGroup     *group;
    SoNode      *node;
    int         index, i;
    SbBool      isTailGroup,  isTailKit;
    SbBool      existedBefore = FALSE;
    SoPath      *pathToXform = NULL;

    editXform = NULL;

    isTailGroup =
	    (   selectionPath->getTail()->isOfType(SoGroup::getClassTypeId() )
	    && !selectionPath->getTail()->isOfType(SoSwitch::getClassTypeId()));

    isTailKit = selectionPath->getTail()->isOfType(SoBaseKit::getClassTypeId());

    //    CASE 1: The path-tail is a node kit.
    if ( isTailKit ) {

	// Nodekits have their own built in policy for creating new transform
	// nodes. Allow them to contruct and return a path to it.
	SoBaseKit *kit = (SoBaseKit *) 
			 ((SoNodeKitPath *)selectionPath)->getTail();

	// Before creating path, see if the transform part exists yet:
	if (SO_CHECK_PART(kit, "transform", SoTransform) != NULL)
	    existedBefore = TRUE;

	if ((editXform = SO_GET_PART(kit, "transform", SoTransform)) != NULL) {
	    pathToXform = kit->createPathToPart( "transform", TRUE, selectionPath );
	    pathToXform->ref();
	}
	else {
	    // This nodekit has no transform part. 
	    // Treat the object as if it were not a nodekit.
	    isTailKit = FALSE;
	}
    }
    
    if ( !isTailGroup && !isTailKit ) {
	//
        //    CASE 2: The path-tail is not a group.
        //    'group'      becomes the second to last node in the path.
        //    We search the path tail and its siblings from right to left for a
        //    transform node.
        //    We stop the search if we come to a 'movable' node
        //    to the left of the pathTail.  If we find a movable node, we
        //    will insert a transform just before the path-tail. This is
        //    because the manipulator should not affect objects that appear
        //    before selectionPath in the scene graph.
	//
        group      = (SoGroup *) selectionPath->getNode(pathLength - 2);
        index      = group->findChild( selectionPath->getTail() );

        for (i = index; (i >= 0) && (editXform == NULL); i--){
            node = group->getChild(i);
            if (node->isOfType(SoTransform::getClassTypeId()))  // found an SoMaterial
                editXform = (SoTransform *) node;
            else if ( i != index ) { 
		if ( isAffectedByTransform( node ) )
		    break;
            }
        }

        if ( editXform == NULL ) {
	    existedBefore = FALSE;
            editXform = new SoTransform;
            group->insertChild( editXform, index );
        }
	else
	    existedBefore = TRUE;
    }
    else if ( !isTailKit ) {
        //    CASE 3: The path-tail is a group.
        //    'group'      becomes the path tail
        //      We search the children from left to right for transform nodes.
        //      We stop the search if we come to a movable node.
        //      If we find a movable node, we will insert a transform just
        //      before this node. This is because the editor
        //      for a group should affect ALL objects within that group.
	//
        group = (SoGroup *) selectionPath->getTail();
        for (i = 0; (i < group->getNumChildren()) && (editXform == NULL); i++ ) {
            node = group->getChild(i);
            if (node->isOfType(SoTransform::getClassTypeId()))
                editXform = (SoTransform *) node;
            else if ( isAffectedByTransform( node ) )
                break;
        }

        if ( editXform == NULL ) {
	    existedBefore = FALSE;
            editXform = new SoTransform;
            group->insertChild( editXform, i );
        }
	else
	    existedBefore = TRUE;
    }

    // If we don't have a path yet (i.e., we weren't handed a nodekit path)
    // create the 'pathToXform'
    // by copying editPath and making the last node in the path be editXform
    if ( pathToXform == NULL ) {
	if ( !isTailGroup )
	    // CASE 2: path-tail was NOT 'group' -- copy all but last entry
	    pathToXform = selectionPath->copy(0, pathLength - 1);
	else
	    // CASE 3: path-tail was 'group' -- copy all of editPath
	    pathToXform = selectionPath->copy(0, pathLength);
	pathToXform->ref();

	// add the transform to the end
	int xfIndex    = group->findChild(editXform);
	pathToXform->append( xfIndex );
    }


    // Now. If we created the transform node right here, right now, then
    // we will set the 'center' field based on the geometric center. We 
    // don't do this if we didn't create the transform, because "maybe it
    // was that way for a reason."
    if ( existedBefore == FALSE ) {
	// First, find 'applyPath' by popping nodes off the path until you 
	// reach a separator. This path will contain all nodes affected by
	// the transform at the end of 'pathToXform'
	SoFullPath *applyPath = (SoFullPath *) pathToXform->copy();
	applyPath->ref();
	for (int i = (applyPath->getLength() - 1); i >0; i-- ) {
	    if (applyPath->getNode(i)->isOfType( SoSeparator::getClassTypeId()))
		break;
	    applyPath->pop();
	}

	// Next, apply a bounding box action to applyPath, and reset the
	// bounding box just before the tail of 'pathToXform' (which is just
	// the editXform). This will assure that the only things included in 
	// the resulting bbox will be those affected by the editXform.
	SoGetBoundingBoxAction bboxAction(currentViewer->getViewportRegion());
	bboxAction.setResetPath(pathToXform,TRUE,SoGetBoundingBoxAction::BBOX );
	bboxAction.apply(applyPath);

	applyPath->unref();

	// Get the center of the bbox in world space...
	SbVec3f worldBoxCenter = bboxAction.getBoundingBox().getCenter();

	// Convert it into local space of the transform...
	SbVec3f localBoxCenter;
	SoGetMatrixAction ma(currentViewer->getViewportRegion());
	ma.apply( pathToXform );
	ma.getInverse().multVecMatrix( worldBoxCenter, localBoxCenter );

	// Finally, set the center value...
	editXform->center.setValue( localBoxCenter );
    }

    pathToXform->unrefNoDelete();
    return( pathToXform );
}


////////////////////////////////////////////////////////////////////////
//
// Description:
//	Create a material editor for the currently selected object.
//
// Use: private
void
SoSceneViewer::createMaterialEditor()
//
////////////////////////////////////////////////////////////////////////
{
    if (materialEditor == NULL)
    	materialEditor = new SoXtMaterialEditor;
    materialEditor->show();
    
    materialEditor->attach( findMaterialForAttach( NULL ) );
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Create a transform editor for the currently selected object
//
// Use: private
void
SoSceneViewer::createTransformSliderSet()
//
////////////////////////////////////////////////////////////////////////
{
    SoPath      *editTransformPath;
    SoTransform *editTransform;

    // get path to a transform to edit
    if ( ( editTransformPath = findTransformForAttach( NULL )) == NULL )
	return;

    // the tail of the path is a transform for us!
    editTransformPath->ref();
    editTransform =(SoTransform *) ((SoFullPath *)editTransformPath)->getTail();
    editTransformPath->unref();
	
    // Nuke the old slider set and get a new one
    if (transformSliderSet == NULL)
	transformSliderSet = new SoXtTransformSliderSet();
    transformSliderSet->setNode(editTransform);
    transformSliderSet->show();
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//      Set fog on/off. Leave density alone - when default, the environment
// node will do something useful to make the fog look good.
//
// Use: private
void
SoSceneViewer::setFog(SbBool flag)
//
////////////////////////////////////////////////////////////////////////
{
    fogFlag = flag;
    
    if (fogFlag)
         environment->fogType.setValue( SoEnvironment::HAZE ); // purple ?
    else environment->fogType.setValue( SoEnvironment::NONE );
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//      Set AA-ing on/off.
//
// Use: private
void
SoSceneViewer::setAntialiasing(SbBool flag)
//
////////////////////////////////////////////////////////////////////////
{
    antialiasingFlag = flag;
    
    if (antialiasingFlag)
	currentViewer->setAntialiasing( TRUE, 3 );
    else
	currentViewer->setAntialiasing( FALSE, 1 );
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//      Invokes color editor on ambient lighting color.
void
SoSceneViewer::editAmbientColor()
//
////////////////////////////////////////////////////////////////////////
{ 
    if ( ambientColorEditor == NULL ) {
    	ambientColorEditor = new MyColorEditor;
	ambientColorEditor->setTitle( "Ambient Lighting" );
	ambientColorEditor->addColorChangedCallback(
	    SoSceneViewer::ambientColorCallback, this );
    }
    
    // Normalize ambient intensity
    SbColor ambCol;
    ambCol = environment->ambientColor.getValue();
    ambCol *= environment->ambientIntensity.getValue();
    environment->ambientIntensity.setValue( 1.0 );
    environment->ambientColor.setValue( ambCol );
    
    ignoreCallback = TRUE;
    ambientColorEditor->setColor( environment->ambientColor.getValue() );
    ignoreCallback = FALSE;
    ambientColorEditor->show();
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//  Callback proc invoked by the color editor, this changes the scene's
//  ambient lighting color.
//
//  Use: static, private
//
void
SoSceneViewer::ambientColorCallback(void *userData, const SbColor *color)
//
////////////////////////////////////////////////////////////////////////
{
    SoSceneViewer *sv = (SoSceneViewer *) userData;
    
    if (sv->ignoreCallback)
    	return;
    
    sv->environment->ambientColor.setValue( *color );
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//      Invokes color editor on background color.
void
SoSceneViewer::editBackgroundColor()
//
////////////////////////////////////////////////////////////////////////
{ 
    if ( backgroundColorEditor == NULL ) {
    	backgroundColorEditor = new MyColorEditor;
	backgroundColorEditor->setTitle( "Background Color" );
	backgroundColorEditor->addColorChangedCallback(
	    SoSceneViewer::backgroundColorCallback, this );
    }
    ignoreCallback = TRUE;
    backgroundColorEditor->setColor(getBackgroundColor());
    ignoreCallback = FALSE;
    backgroundColorEditor->show();
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//  Callback proc invoked by the color editor, this changes the current
//  viewer's background color.
//
//  Use: static, private
//
void
SoSceneViewer::backgroundColorCallback(void *userData, const SbColor *c)
//
////////////////////////////////////////////////////////////////////////
{
//??? should be using the Roxy color editor, not the So color editor

    SoSceneViewer *sv = (SoSceneViewer *) userData;
    
    if (sv->ignoreCallback)
    	return;
    
    sv->currentViewer->setBackgroundColor( *c );
    
    // keep fog color up to date with bkg color
    sv->environment->fogColor.setValue( *c );
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	This will:
//        [a] find the last sceneKit camera that is being looked through
//            in the scene and return  a pointer to it.
//
// Use: private
SoCamera *
SoSceneViewer::getLastSceneKitCamera(SoGroup *root)
//
////////////////////////////////////////////////////////////////////////
{
    // Find scene kits under the root node and loop backwards:
    SoSearchAction sa;
    sa.setType(SoSceneKit::getClassTypeId());
    sa.setInterest(SoSearchAction::ALL);
    sa.apply(root);

    SoPathList paths = sa.getPaths();
    for (int i = paths.getLength() - 1; i >= 0; i--) {
	SoPath *p = paths[i];
	if (p->getTail()->isOfType( SoSceneKit::getClassTypeId() ) ) {
	    SoSceneKit *sceneKit = (SoSceneKit *) p->getTail();
	    int camNum = sceneKit->getCameraNumber();

	    SoNodeKitListPart *camList = 
		(SoNodeKitListPart *) sceneKit->getPart("cameraList",FALSE);
	    if (camList && camNum >= 0) {
	        SoCameraKit *camKit 
		    = (SoCameraKit *)camList->getChild( camNum );
		if (camKit)
		    return( (SoCamera *) camKit->getPart( "camera", FALSE ));
	    }
	}
    }
    return NULL;
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	This will:
//        [a] find the last sceneKit, its camera number, and replace the
//            given camera for that node.
//
// Use: private
void
SoSceneViewer::setLastSceneKitCamera(SoGroup *root, SoCamera *theCam)
//
////////////////////////////////////////////////////////////////////////
{
    // Find scene kits under the root node and loop backwards:
    SoSearchAction sa;
    sa.setType(SoSceneKit::getClassTypeId());
    sa.setInterest(SoSearchAction::ALL);
    sa.apply(root);

    SoPathList paths = sa.getPaths();
    for (int i = paths.getLength() - 1; i >= 0; i--) {
	SoPath *p = paths[i];
	if (p->getTail()->isOfType( SoSceneKit::getClassTypeId() ) ) {
	    SoSceneKit *sceneKit = (SoSceneKit *) p->getTail();
	    int camNum = sceneKit->getCameraNumber();

	    SoNodeKitListPart *camList = 
		(SoNodeKitListPart *) sceneKit->getPart("cameraList",FALSE);
	    if (camList && camNum >= 0) {
	        SoCameraKit *camKit 
		    = (SoCameraKit *)camList->getChild( camNum );
		if (camKit) {
		    camKit->setPart("camera",theCam);
		    return;
		}
	    }
	}
    }
    return;
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	This will:
//        [a] find scene kits if under the root node.
//        [b] Save the camera number settings of the kits in a dictionary.
//        [c] Switch off the scenekit cameras.
//
// Use: private
void
SoSceneViewer::switchOffSceneKitCameras(SoGroup *root)
//
////////////////////////////////////////////////////////////////////////
{
    // [a] find scene kits if under the root node.
    SoSearchAction sa;
    sa.setType(SoSceneKit::getClassTypeId());
    sa.setInterest(SoSearchAction::ALL);
    sa.apply(root);
    
    // Deal with each kit:
    SoPathList paths = sa.getPaths();
    for (int i = paths.getLength() - 1; i >= 0; i--) {
	SoPath *p = paths[i];
	if (p->getTail()->isOfType( SoSceneKit::getClassTypeId() ) ) {
	    SoSceneKit *sceneKit = (SoSceneKit *) p->getTail();
	    int *camNumPtr = new int;
	    *camNumPtr = sceneKit->getCameraNumber();

	    // [b] Save the camera number settings of the kits in a dictionary.
	    sceneKitCamNumDict->enter((unsigned long)sceneKit,
				      (void *)camNumPtr);

	    // [c] Switch off the scenekit cameras.
	    sceneKit->setCameraNumber( SO_SWITCH_NONE );
	}
    }
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	This will:
//        [a] find scene kits if under the root node.
//        [b] Find the camera number settings of the kits from a dictionary.
//        [c] Restore the sceneKit camera numbers.
//
// Use: private
void
SoSceneViewer::restoreSceneKitCameras(SoGroup *root)
//
////////////////////////////////////////////////////////////////////////
{
    // [a] find scene kits if under the root node.
    SoSearchAction sa;
    sa.setType(SoSceneKit::getClassTypeId());
    sa.setInterest(SoSearchAction::ALL);
    sa.apply(root);
    
    // Deal with each kit:
    SoPathList paths = sa.getPaths();
    for (int i = paths.getLength() - 1; i >= 0; i--) {
	SoPath *p = paths[i];
	if (p->getTail()->isOfType( SoSceneKit::getClassTypeId() ) ) {
	    SoSceneKit *sceneKit = (SoSceneKit *) p->getTail();
	    void *myPtr;
	    int camNum;
	    if (sceneKitCamNumDict->find((unsigned long)sceneKit, myPtr))
		camNum = *((int *)myPtr);
	    else
		camNum = SO_SWITCH_NONE;

	    sceneKit->setCameraNumber( camNum );
	}
    }
}

////////////////////////////////////////////////////////////////////////
//
// Description:
// Copies from given camera into this viewer's camera, if types match.
//
// Use: private
void        
SoSceneViewer::setCameraFields( SoCamera *fromCam )
//
////////////////////////////////////////////////////////////////////////
{
    SoCamera *myCam = getCamera();

    if ( ! myCam || ! fromCam )
	return;

    // Types must match!
    if (  myCam->getTypeId() != fromCam->getTypeId() )
	return;

    myCam->viewportMapping = fromCam->viewportMapping.getValue();
    myCam->position = fromCam->position.getValue();
    myCam->orientation = fromCam->orientation.getValue();
    myCam->aspectRatio = fromCam->aspectRatio.getValue();
    myCam->nearDistance = fromCam->nearDistance.getValue();
    myCam->farDistance = fromCam->farDistance.getValue();
    myCam->focalDistance = fromCam->focalDistance.getValue();

    if (   myCam->isOfType( SoPerspectiveCamera::getClassTypeId() )) {
	((SoPerspectiveCamera *)myCam)->heightAngle 
	    = ((SoPerspectiveCamera *)fromCam)->heightAngle.getValue();
    }
    else if (   myCam->isOfType( SoOrthographicCamera::getClassTypeId() )) {
	((SoOrthographicCamera *)myCam)->height 
	    = ((SoOrthographicCamera *)fromCam)->height.getValue();
    }
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	This will remove any cameras under root.
//
// Use: private
void
SoSceneViewer::removeCameras(SoGroup *root)
//
////////////////////////////////////////////////////////////////////////
{
    SoSearchAction sa;
    sa.setType(SoCamera::getClassTypeId());
    sa.setInterest(SoSearchAction::ALL);
    sa.apply(root);
    
    // remove those cameras!
    SoPathList paths = sa.getPaths();
    for (int i = 0; i < paths.getLength(); i++) {
	SoPath *p = paths[i];
	int cam = p->getIndexFromTail(0);
	SoGroup  *group = (SoGroup *) p->getNodeFromTail(1);
	group->removeChild(cam);
	
	// See if the parent of this camera is a switch node with whichChild set
	// to render the camera. With the camera gone, the switch has nothing
	// to render.
	if (group->isOfType(SoSwitch::getClassTypeId())) {
	    SoSwitch *sw = (SoSwitch *) group;
	    if (sw->whichChild.getValue() == cam)
		sw->whichChild.setValue(SO_SWITCH_NONE);
	}
    }
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Reads the given file and insert the geometry under the selection
//  node. If the node didn't have any children, the viewAll() method is
//  automatically called.
//
// Use: private
SbBool
SoSceneViewer::readFile(const char *filename)
//
////////////////////////////////////////////////////////////////////////
{    
    SbBool hadNoChildren = (selection->getNumChildren() == 0);
    
    // Try reading the file
    SbString errorMessage;
    SoSeparator *sep = MyFileRead(filename, errorMessage);

    // add nodes under selection, not sceneGraph
    if (sep != NULL)
	selection->addChild(sep);
    
    // display error dialog if there were reading errors
    else {
	SoXt::createSimpleErrorDialog(mgrWidget, "File Error Dialog", 
		    (char *) errorMessage.getString());
	return FALSE;
    }
    
    // remove any cameras under selection which were just added
    SoCamera *camFromScene = getLastSceneKitCamera(selection);
    switchOffSceneKitCameras(selection);
    removeCameras(selection);
    
    if (hadNoChildren) {
	viewAll();
	saveHomePosition();
    }

    // If scene had sceneKit with a camera, copy its values into our camera.
    if (camFromScene)
	setCameraFields( camFromScene );
    
    return TRUE;
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Read environment data. We expect the following nodes:
//
//  Group {
//    Label { "SoSceneViewer Environment v3.0" }
//    Camera {}
//    Environment {}
//    LightGroup {
//      Switch { DirectionalLight }  # 1
//  	...
//      Switch { DirectionalLight }  # 6
//    }
//    DirectionalLight {}   	# optional headlight
//  }
//
// Use: private
SbBool
SoSceneViewer::readEnvFile(const char *filename)
//
////////////////////////////////////////////////////////////////////////
{
    SoInput in;
    if (! in.openFile(filename)) {
	// display an error dialog
	char str[100];
	strcpy(str, "Error opening file: ");
	strcat(str, filename);
	SoXt::createSimpleErrorDialog(mgrWidget, "File Error Dialog", str);
	return FALSE;
    }
    
    SoNode *n;
    SoLabel *l = NULL;
    SbBool isValid = FALSE;
    SbBool ok;
    
    if ((ok = SoDB::read(&in, n)) && n != NULL) {
	// we expect a label first
	n->ref();
	if (n->isOfType(SoLabel::getClassTypeId())) {
	    l = (SoLabel *) n;
	    isValid = (strcmp(l->label.getValue().getString(),
			      SV_ENV_LABEL) == 0);
	}
	n->unref();
    }
    else if (!ok) {
	// display error dialog if there were reading errors
	char str[100];
	strcpy(str, "Error reading file: ");
	strcat(str, filename);
	SoXt::createSimpleErrorDialog(mgrWidget, "File Error Dialog", str);
	return FALSE;
    }

    // if ok, read the rest.
    if (isValid) {
	// Camera
	if (SoDB::read(&in, n) != FALSE && (n != NULL)) {
	    n->ref();
	    if (n->isOfType(SoCamera::getClassTypeId())) {
		// replace the old camera with the new camera and
		// re-attach the viewer.
		SoCamera *newCamera = (SoCamera *) n;
		SoCamera *oldCamera = getCamera();
		SoSearchAction sa;
		sa.setNode(oldCamera);
		sa.apply(sceneGraph);
		SoFullPath *fullCamPath = (SoFullPath *) sa.getPath();
		if (fullCamPath) {
		    SoGroup *parent = 
			(SoGroup *)fullCamPath->getNode(fullCamPath->getLength() - 2);
		    parent->insertChild(newCamera, parent->findChild(oldCamera));
		    setCamera(newCamera);
		    if (parent->findChild(oldCamera) >= 0)
			parent->removeChild(oldCamera);
		}
#if DEBUG
		else
		    SoDebugError::post("SoSceneViewer::readEnvFile",
			    "cannot find camera in graph");
#endif
	    }
	    n->unref();
	}
	// Environment
	if (SoDB::read(&in, n) != FALSE && (n != NULL)) {
	    n->ref();
	    if (n->isOfType(SoEnvironment::getClassTypeId())) {
		lightsCameraEnvironment->replaceChild(environment, n);
		environment = (SoEnvironment *) n;
	    }
	    n->unref();
	}
	// Light group
	if (SoDB::read(&in, n) != FALSE && (n != NULL)) {
	    n->ref();
	    if (n->isOfType(SoGroup::getClassTypeId())) {
		
		// remove all of the existing lights
		int i;
		for (i = lightDataList.getLength(); i > 0; i--)
		    removeLight( (SvLightData *) lightDataList[i-1] );
		
		lightsCameraEnvironment->replaceChild(lightGroup, n);
		lightGroup = (SoGroup *) n;
		
		// This was busted. It was looking for a light as child 0,
		// but the scale and scaleInverse made it think no light was 
		// there. So now, we do this right...
		// We'll just check for the light as any old child.
		// This way it's okay to add a translation node under that 
		// switch too, so we can translate the manips as well.
		// This allows as to place the directional light manips.
		for (i=0; i < lightGroup->getNumChildren(); i++) {
		    SoNode *node = lightGroup->getChild(i);
		    if (node->isOfType(SoSwitch::getClassTypeId())) {
			SoSwitch *sw = (SoSwitch *) node;
			SbBool addedIt = FALSE;
			for (int j = 0; 
			     addedIt == FALSE && j < sw->getNumChildren(); 
			     j++ ) {
			    node = sw->getChild(j);
			    if (node->isOfType(SoLight::getClassTypeId())) {
				addLightEntry((SoLight *)node, sw);
				addedIt = TRUE;
			    }
			}
		    }
		}
	    }
	    n->unref();
	}
	// Headlight (optional) - if not there, turn headlight off
	if (SoDB::read(&in, n) != FALSE && (n != NULL)) {
	    n->ref();
	    if (n->isOfType(SoDirectionalLight::getClassTypeId())) {
		SoDirectionalLight *headlight = getHeadlight();
		SoDirectionalLight *newLight = (SoDirectionalLight *) n;
		if (headlight != NULL) {
		    headlight->intensity.setValue(newLight->intensity.getValue());
		    headlight->color.setValue(newLight->color.getValue());
		    headlight->direction.setValue(newLight->direction.getValue());
		    setHeadlight(TRUE);
		}
	    }
	    n->unref();
	}
	else setHeadlight(FALSE);
    }
    else {
	fprintf(stderr, "Sorry, file is not formatted correctly\n");
    }
    
    return TRUE;
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	This routine is called to get a file name using the
// standard file dialog.
//
// Use: private
void
SoSceneViewer::getFileName()
//
////////////////////////////////////////////////////////////////////////
{
    // use a motif file selection dialog
    if (fileDialog == NULL) {
	Arg args[5];
	int n = 0;
	
	// unmanage when ok/cancel are pressed
	XtSetArg(args[n], XmNautoUnmanage, TRUE); n++;
	fileDialog = XmCreateFileSelectionDialog(
	    XtParent(mgrWidget), "File Dialog", args, n);
	
	XtAddCallback(fileDialog, XmNokCallback,
		      (XtCallbackProc)SoSceneViewer::fileDialogCB,
		      (XtPointer)this);
    }
    
    // manage the dialog
    XtManageChild(fileDialog);
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Motif file dialog callback.
//
void
SoSceneViewer::fileDialogCB(Widget, SoSceneViewer *sv,
		      XmFileSelectionBoxCallbackStruct *data)
//
////////////////////////////////////////////////////////////////////////
{
    // Get the file name
    char *filename;
    XmStringGetLtoR(data->value,
	(XmStringCharSet) XmSTRING_DEFAULT_CHARSET, &filename);
    
    // Use that file
    sv->doFileIO(filename);
    
    XtFree(filename);
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	detach everything and nuke the existing scene.
//
// Use: private
void
SoSceneViewer::deleteScene()
//
////////////////////////////////////////////////////////////////////////
{
    // deselect everything (also detach manips)
    selection->deselectAll();
    
    // remove the geometry under the selection node
    for (int i = selection->getNumChildren(); i>0; i--)
	selection->removeChild(i-1);
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Read/Write to the given file name, given the current file mode.
//
// Use: private
SbBool
SoSceneViewer::doFileIO(const char *file)
//
////////////////////////////////////////////////////////////////////////
{
    SbBool okFile = TRUE;
    
    switch (fileMode) {
	case SV_FILE_OPEN:
	    deleteScene();
	    okFile = readFile(file);
	    // If we've already made lights, re-calculate size for light 
	    // manips based on size of new scene.
	    if (calculatedLightManipSize)
		calculateLightManipSize();
	    break;
	case SV_FILE_IMPORT:
	    okFile = readFile(file);
	    // If we've already made lights, re-calculate size for light 
	    // manips based on size of new scene.
	    if (calculatedLightManipSize)
		calculateLightManipSize();
	    break;
	case SV_FILE_SAVE_AS:
	    okFile = writeFile(file);
	    break;
	case SV_FILE_READ_ENV:
	    readEnvFile(file);
	    break;
	case SV_FILE_SAVE_ENV:
	    {
	    
	    // Run through the lights. If any light is a directionalLightManip,
	    // transfer its translation into the SvLightData, since that
	    // info will not write out.
	    for (int i=0; i < lightDataList.getLength(); i++)
		transferDirectionalLightLocation((SvLightData *) lightDataList[i]);

	    writeEnvFile(file);
	    }

	    break;
	default:
	    fprintf(stderr, "Wrong file mode %d passed!\n", fileMode);
	    return FALSE;
    }
    
    // save the new file name so we can simply use "Save" instead of
    // "Save As" next time around.
    if (fileMode == SV_FILE_OPEN || fileMode == SV_FILE_SAVE_AS) {
	
	// save the current file name
	delete fileName;
	if (okFile && file != NULL)
	    fileName = strdup(file);
	else
	    fileName = NULL;
    }
    
    // enable/disable cmd key shortcuts and menu items
    updateCommandAvailability();
    
    return okFile;
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Saves the scene to the current file.
//
// Use: private
void
SoSceneViewer::save()
//
////////////////////////////////////////////////////////////////////////
{
    if (fileName != NULL) {
	SbBool ok = writeFile(fileName);
	if (!ok) {
	    delete fileName;
	    fileName = NULL;
	}
    }
    else {
	fileMode = SV_FILE_SAVE_AS;
	getFileName();
    }
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Removes the attached light manips geometry from the scene. This
//  is used for file writting,...
//
// Use: private
void
SoSceneViewer::removeAttachedLightManipGeometry()
//
////////////////////////////////////////////////////////////////////////
{
    for (int i = 0; i < lightDataList.getLength(); i++ ) {
	
	SvLightData *data = (SvLightData *) lightDataList[i];

	// We'll be putting everything back later, so make a note of this...
	data->shouldBeManip = data->isManip();

	if ( data->isManip() == TRUE )
	    editLight(data, FALSE);
    }
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Add the attached light manips geometry back into the scene. This
// is called after the geometry has been temporaly revomed (used for file
// writting).
//
// Use: private
void
SoSceneViewer::addAttachedLightManipGeometry()
//
////////////////////////////////////////////////////////////////////////
{
    for (int i = 0; i < lightDataList.getLength(); i++ ) {
	
	SvLightData *data = (SvLightData *) lightDataList[i];

	if ( data->isManip() != data->shouldBeManip )
	    editLight(data, data->shouldBeManip);
    }
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Write the nodes under the selection node to the given file name.
//
// Use: private
SbBool
SoSceneViewer::writeFile(const char *filename)
//
////////////////////////////////////////////////////////////////////////
{
    SoWriteAction   wa;
    
    if (! wa.getOutput()->openFile(filename)) {
	
	// display an error dialog
	char str[100];
	strcpy(str, "Error creating file: ");
	strcat(str, filename);
	SoXt::createSimpleErrorDialog(mgrWidget, "File Error Dialog", str);
	
	return FALSE;
    }
    
    // temporarily replace all manips with regular transform nodes.
    removeManips();

    // restore the cameraNum settings of any scenekits.  
    restoreSceneKitCameras(selection);
    // Copy our camera into the last sceneKit.
    setLastSceneKitCamera(selection, (SoCamera *)getCamera()->copy());

    // write out all the children of the selection node
    for (int i = 0; i < selection->getNumChildren(); i++)
	wa.apply(selection->getChild(i));
    wa.getOutput()->closeFile();
    
    // Switch the sceneKit cameras back off:
    switchOffSceneKitCameras(selection);

    // Now put the manips back in the scene graph.
    restoreManips();
    
    return TRUE;
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Write the Enviroment nodes (camera and lights) to the given 
//  file name.
//
// Use: private
SbBool
SoSceneViewer::writeEnvFile(const char *filename)
//
////////////////////////////////////////////////////////////////////////
{
    SoWriteAction	wa;
    
    if (! wa.getOutput()->openFile(filename)) {
	
	// display an error dialog
	char str[100];
	strcpy(str, "Error creating file: ");
	strcat(str, filename);
	SoXt::createSimpleErrorDialog(mgrWidget, "File Error Dialog", str);

	return FALSE;
    }
    
    // write out the environment including the headlight
    wa.apply(envLabel);
    wa.apply(getCamera());
    wa.apply(environment);
    wa.apply(lightGroup);
    if (isHeadlight())
	wa.apply(getHeadlight());
    
    wa.getOutput()->closeFile();
    
    return TRUE;
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Print the scene using a custom print dialog.
//
// Use: private
void
SoSceneViewer::print()
//
////////////////////////////////////////////////////////////////////////
{
    if (printDialog == NULL) {
    	printDialog = new SoXtPrintDialog;
	printDialog->setTitle("SceneViewer Printing");
	printDialog->setBeforePrintCallback(
	    SoSceneViewer::beforePrintCallback, (void *) this);
	printDialog->setAfterPrintCallback(
	    SoSceneViewer::afterPrintCallback, (void *) this);
    }
    
    //
    // Send the render area size and scene graph to the print dialog
    //
    Widget widget = getRenderAreaWidget();
    if (widget != NULL) {
        Arg args[2];
        int n = 0;
        SbVec2s sz;
        XtSetArg(args[n], XtNwidth, &sz[0]); n++;
        XtSetArg(args[n], XtNheight, &sz[1]); n++;
        XtGetValues(widget, args, n);
        printDialog->setPrintSize(sz);
    }
    
    printDialog->show();
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Temporarily remove manips from the scene.
// Restore them with a call to restoreManips().
//
// Use: private
void
SoSceneViewer::removeManips()
//
////////////////////////////////////////////////////////////////////////
{
    // temporarily replace all manips with regular transform nodes.
    for (int m = 0; m < maniplist->getLength(); m++ ) {
	SoTransformManip *manip = maniplist->getManip(m);	
	SoPath *xfPath = maniplist->getXfPath(m);
	manip->replaceManip(xfPath, NULL);
    }
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Restore manips that were removed with removeManips().
//
// Use: private
void
SoSceneViewer::restoreManips()
//
////////////////////////////////////////////////////////////////////////
{
    // Now put the manips back in the scene graph.
    for (int m = 0; m < maniplist->getLength(); m++ ) {
	SoTransformManip *manip = maniplist->getManip(m);	
	SoPath *xfPath = maniplist->getXfPath(m);
	manip->replaceNode(xfPath);
    }
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Temporarily remove manips from the scene. They
// will all be restored after the printing is done.
//
// Use: private, static
void
SoSceneViewer::beforePrintCallback(void *uData, SoXtPrintDialog *)
//
////////////////////////////////////////////////////////////////////////
{
    SoSceneViewer *sv = (SoSceneViewer *)uData;
    
    // temporarily replace all manips with regular transforms.
    sv->removeManips();

    // Do the same for all the light manips
    sv->removeAttachedLightManipGeometry();
    
    // if the current viewer is the examiner viewer, turn the 
    // feedback axis off while we print
    if (sv->whichViewer == SV_VWR_EXAMINER) {
	SoXtExaminerViewer *exam = (SoXtExaminerViewer *) sv->currentViewer;
	sv->feedbackShown = exam->isFeedbackVisible();
	exam->setFeedbackVisibility(FALSE);
    }
    
    // set the scene to print
    sv->printDialog->setSceneGraph(sv->sceneGraph);
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Called after printing is done. Add the manips back into the
// scene.
//
// Use: private, static
void
SoSceneViewer::afterPrintCallback(void *uData, SoXtPrintDialog *)
//
////////////////////////////////////////////////////////////////////////
{
    SoSceneViewer *sv = (SoSceneViewer *)uData;
    
    // put the manips back in the scene graph.
    sv->restoreManips();
    
    // put the light manips back in the scene graph.
    sv->addAttachedLightManipGeometry();
    
    // restor the examiner feedback
    if (sv->whichViewer == SV_VWR_EXAMINER) {
	SoXtExaminerViewer *exam = (SoXtExaminerViewer *) sv->currentViewer;
	exam->setFeedbackVisibility( sv->feedbackShown );
    }
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Static routine for processing topbar menu events.
//  When the menu is created, it stores pointer to the SoSceneViewer
//  in the client_data, so that we can tell which SoSceneViewer needs
//  the event.
//
// Use: private, static
//
void
SoSceneViewer::processTopbarEvent(
	Widget,				// Which widget?  I don't care
	SoSceneViewerData *data,	// Pointer to button/SoSceneViewer
	XmAnyCallbackStruct *cb )	// X garbage
//
////////////////////////////////////////////////////////////////////////
{
    SoSceneViewer *sv = data->classPt;
    Time eventTime = cb->event->xbutton.time;
    
    switch (data->id) {
    
    //
    // File
    //
    
    case SV_FILE_ABOUT:
	sv->showAboutDialog();
	break;
	
    case SV_FILE_NEW:
	sv->deleteScene();
	delete sv->fileName;
	sv->fileName = NULL;
	break;
	
    case SV_FILE_OPEN:
    case SV_FILE_IMPORT:
    case SV_FILE_SAVE_AS:
    case SV_FILE_READ_ENV:
    case SV_FILE_SAVE_ENV:
	sv->fileMode = data->id;
	sv->getFileName();
	break;
	
    case SV_FILE_SAVE:
	sv->save();
	break;
	
    case SV_FILE_PRINT:
    	sv->print();
	break;
    case SV_FILE_QUIT:
	delete sv;
	exit(0);
	break;
	
    //
    // Edit
    //
    
    case SV_EDIT_PICK_PARENT:
	sv->pickParent();
	break;
    case SV_EDIT_PICK_ALL:
	sv->pickAll();
	break;
    case SV_EDIT_CUT:
	// Remove manipulators before cutting the selection.
	sv->detachManipFromAll();
	sv->clipboard->copy((SoPathList *)sv->selection->getList(), eventTime);
	sv->destroySelectedObjects();
	sv->updateCommandAvailability();
	break;
    case SV_EDIT_COPY:
	// Remove manipulators while copying the selection.
	sv->removeManips();
	sv->clipboard->copy((SoPathList *)sv->selection->getList(),  eventTime);
	sv->restoreManips();
	break;
    case SV_EDIT_PASTE:
	sv->clipboard->paste(eventTime, pasteDoneCB, sv);
	break;
    case SV_EDIT_DELETE:
	sv->destroySelectedObjects();
	sv->updateCommandAvailability();
	break;
    
    //
    // Viewing
    //
    
    case SV_VIEW_PICK:
	sv->setViewing(! sv->isViewing());
	break;
#ifdef EXPLORER
    case SV_VIEW_USER:
	sv->userModeFlag = !sv->userModeFlag;
	if (sv->userModeFlag)
	    sv->currentViewer->setEventCallback(sv->userModeCB, sv->userModedata);
	else
	    sv->currentViewer->setEventCallback(NULL, NULL);
	break;
#endif
    
    case SV_VIEW_EXAMINER:
	sv->switchToViewer(SV_VWR_EXAMINER);
	break;
    case SV_VIEW_WALK:
	sv->switchToViewer(SV_VWR_WALK);
	break;
    case SV_VIEW_PLANE:
	sv->switchToViewer(SV_VWR_PLANE);
	break;
    case SV_VIEW_FLY:
	sv->switchToViewer(SV_VWR_FLY);
	break;
	
    case SV_VIEW_SELECTION:
        sv->viewSelection();
        break;

    case SV_VIEW_SCREEN_TRANSPARENCY:
	sv->setTransparencyType(SoGLRenderAction::SCREEN_DOOR);
	break;
    case SV_VIEW_BLEND_TRANSPARENCY:
	sv->setTransparencyType(SoGLRenderAction::BLEND);
	break;
    case SV_VIEW_DELAY_BLEND_TRANSPARENCY:
	sv->setTransparencyType(SoGLRenderAction::DELAYED_BLEND);
	break;
    case SV_VIEW_SORT_BLEND_TRANSPARENCY:
	sv->setTransparencyType(SoGLRenderAction::SORTED_OBJECT_BLEND);
	break;

    case SV_VIEW_FOG:
        sv->setFog(! sv->fogFlag);
        break;
    case SV_VIEW_ANTIALIASING:
        sv->setAntialiasing(! sv->antialiasingFlag);
        break;
    case SV_VIEW_BKG_COLOR:
        sv->editBackgroundColor();
        break;


    //
    // Editors
    //
    case SV_EDITOR_MATERIAL:
	sv->createMaterialEditor();
	break;

    case SV_EDITOR_TRANSFORM:
	sv->createTransformSliderSet();
	break;

    case SV_EDITOR_COLOR:
	sv->createColorEditor();
	break;

    //
    // Selection
    //
    case SV_SEL_SINGLE_SELECT:
    	sv->selection->policy.setValue(SoSelection::SINGLE);
	break;

    case SV_SEL_TOGGLE_SELECT:
    	sv->selection->policy.setValue(SoSelection::TOGGLE);
	break;

    case SV_SEL_SHIFT_SELECT:
    	sv->selection->policy.setValue(SoSelection::SHIFT);
	break;

    //
    // Manips
    //
    case SV_MANIP_TRANSFORMER:
	sv->highlightRA->setVisible(FALSE); // highlight visible when no manip
	sv->curManip = (sv->curManip == SV_TRANSFORMER) ? SV_NONE : SV_TRANSFORMER;
	if ( sv->curManipReplaces )
	    sv->replaceAllManips( sv->curManip );
        break;

    case SV_MANIP_TRACKBALL:
	sv->highlightRA->setVisible(FALSE); // highlight visible when no manip
	sv->curManip = (sv->curManip == SV_TRACKBALL) ? SV_NONE : SV_TRACKBALL;
	if ( sv->curManipReplaces )
	    sv->replaceAllManips( sv->curManip );
        break;

    case SV_MANIP_HANDLEBOX:
	sv->highlightRA->setVisible(FALSE); // highlight visible when no manip
	sv->curManip = (sv->curManip == SV_HANDLEBOX) ? SV_NONE : SV_HANDLEBOX;
	if ( sv->curManipReplaces )
	    sv->replaceAllManips( sv->curManip );
        break;

    case SV_MANIP_JACK:
	sv->highlightRA->setVisible(FALSE); // highlight visible when no manip
	sv->curManip = (sv->curManip == SV_JACK) ? SV_NONE : SV_JACK;
	if ( sv->curManipReplaces )
	    sv->replaceAllManips( sv->curManip );
        break;

    case SV_MANIP_CENTERBALL:
	sv->highlightRA->setVisible(FALSE); // highlight visible when no manip
	sv->curManip =(sv->curManip == SV_CENTERBALL) ? SV_NONE : SV_CENTERBALL;
	if ( sv->curManipReplaces )
	    sv->replaceAllManips( sv->curManip );
        break;

    case SV_MANIP_XFBOX:
	sv->highlightRA->setVisible(FALSE); // highlight visible when no manip
	sv->curManip = (sv->curManip == SV_XFBOX) ? SV_NONE : SV_XFBOX;
	if ( sv->curManipReplaces )
	    sv->replaceAllManips( sv->curManip );
        break;

    case SV_MANIP_TABBOX:
	sv->highlightRA->setVisible(FALSE); // highlight visible when no manip
	sv->curManip = (sv->curManip == SV_TABBOX) ? SV_NONE : SV_TABBOX;
	if ( sv->curManipReplaces )
	    sv->replaceAllManips( sv->curManip );
        break;

    case SV_MANIP_NONE:
	sv->highlightRA->setVisible(TRUE); // highlight visible when no manip
	sv->curManip = SV_NONE;
	if ( sv->curManipReplaces )
	    sv->detachManipFromAll();
        break;
    case SV_MANIP_REPLACE_ALL:
	// Toggle the value of 'curManipReplaces'
	sv->curManipReplaces = ( sv->curManipReplaces == TRUE) ? FALSE : TRUE;

	if ( sv->curManipReplaces )
	    sv->replaceAllManips( sv->curManip );
        break;
	
    //
    // Lights
    //
    case SV_LIGHT_AMBIENT_EDIT:	sv->editAmbientColor(); break;
    case SV_LIGHT_ADD_DIRECT:	sv->addLight(new SoDirectionalLightManip); break;
    case SV_LIGHT_ADD_POINT:	sv->addLight(new SoPointLightManip); break;
    case SV_LIGHT_ADD_SPOT:	
	{
	    // Set the dropOffRate to be non-zero, or it will always work
	    // like a point light.
	    SoSpotLightManip *newSpotManip = new SoSpotLightManip;
	    newSpotManip->dropOffRate = .01;
	    sv->addLight(newSpotManip); 
	}
	break;
    
    case SV_LIGHT_TURN_ON:
    case SV_LIGHT_TURN_OFF:
	{
	SbBool onFlag = (data->id == SV_LIGHT_TURN_ON);
	for (int i=0; i < sv->lightDataList.getLength(); i++)
	    sv->turnLightOnOff((SvLightData *) sv->lightDataList[i], onFlag);
	sv->turnLightOnOff( sv->headlightData, onFlag);
	}
	break;
    case SV_LIGHT_SHOW_ALL:
    case SV_LIGHT_HIDE_ALL:
	{
	SbBool onFlag = (data->id == SV_LIGHT_SHOW_ALL);
	for (int i=0; i < sv->lightDataList.getLength(); i++)
	    sv->editLight((SvLightData *) sv->lightDataList[i], onFlag);
	}
	break;
    
    } // endswitch( topbar button )
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Adds the given light to the scene and to the menu.
//
// Use: private
//
void
SoSceneViewer::addLight(SoLight *light)
//
////////////////////////////////////////////////////////////////////////
{
    // Calculate the light manip size if necessary.
    // Do this before adding the light into the scene,
    // since if the light is a manip, its default size might influence the
    // scene size.
    if (!calculatedLightManipSize)
	calculateLightManipSize();

    // create the switch and light node and add it to the scene
    SoSwitch *lightSwitch = new SoSwitch;
    lightGroup->addChild(lightSwitch);
    lightSwitch->addChild(light);
    SWITCH_LIGHT_ON(lightSwitch);
    
    // add the light entry for the new light
    SvLightData *data = addLightEntry(light, lightSwitch);

    //
    // Try to come up with some meaningfull default position base
    // of the current camera view volume.
    //
    SoCamera *vwrCamera = getCamera(); // don't cache this in the class
    SbViewVolume vv = vwrCamera->getViewVolume(0.0);
    SbVec3f forward = - vv.zVector();
    SbVec3f center = vwrCamera->position.getValue() + forward * 
	(vwrCamera->nearDistance.getValue() + vwrCamera->farDistance.getValue()) / 2.0;
    SbVec3f position( vv.ulf + forward * vv.nearToFar * .25 );
//XXX ??? XXX
//XXX this algorithm should be replaced. Perhaps instead of using
//XXX 'forward' we could go a little up and to the left?
//XXX ??? XXX
		
    if (data->type.isDerivedFrom(SoDirectionalLight::getClassTypeId())) {
	SoDirectionalLight *myLight = (SoDirectionalLight *) data->light;
	// the position of the light can't be given to the light itself.
	// So we use the translation and translation inverse to 
	// get it to go where we want.
	data->translation->translation = position;
	data->translationInverse->translation = -position;
	myLight->direction = center - position;
    }
    else {
	// The data->scale will influence the position we set.
	// So we need to prepare for this. Note, it's not a prolem for
	// directional lights since they use the translation node,
	// which is outside the scale and scaleInverse grouping
	SbVec3f invrs = data->scaleInverse->scaleFactor.getValue();
	SbVec3f scaledLoc = position;
	scaledLoc *= invrs[0]; 

	if (data->type.isDerivedFrom(SoPointLight::getClassTypeId())) {
	    SoPointLight *myLight = (SoPointLight *) data->light;
	    myLight->location = scaledLoc;
	    // no direction for this light
        }
        else if (data->type.isDerivedFrom(SoSpotLight::getClassTypeId())) {
	    SoSpotLight *myLight = (SoSpotLight *) data->light;
	    myLight->location = scaledLoc;
	    myLight->direction = center - position;
        }
    }
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Creates and append the light data struct, and adds a menu entry
//  for the light.
//
// Use: private
//
SvLightData *
SoSceneViewer::addLightEntry(SoLight *light, SoSwitch *lightSwitch)
//
////////////////////////////////////////////////////////////////////////
{
    //
    // create the light data
    //
    
    SvLightData *data = new SvLightData;
    lightDataList.append(data);

    light->ref();
    data->light = light;

    data->lightSwitch = lightSwitch;

    // Try and find the scale, scaleInverse, translation, and 
    // translationInverse.
    data->scale = NULL;
    data->scaleInverse = NULL;
    data->translation = NULL;
    data->translationInverse = NULL;
    SbBool gotLight = FALSE;
    for ( int i = 0; i < lightSwitch->getNumChildren(); i++ ) {
	SoNode *n = lightSwitch->getChild(i);
	if (n == light)
	    gotLight = TRUE;
	else if (n->isOfType(SoScale::getClassTypeId())){
	    if (data->scale == NULL && gotLight == FALSE)
		data->scale = (SoScale *) n;
	    else if (data->scaleInverse == NULL && gotLight == TRUE)
		data->scaleInverse = (SoScale *) n;
	}
	else if (n->isOfType(SoTranslation::getClassTypeId())){
	    if (data->translation == NULL && gotLight == FALSE)
		data->translation = (SoTranslation *) n;
	    else if (data->translationInverse == NULL && gotLight == TRUE)
		data->translationInverse = (SoTranslation *) n;
	}
    }

    // Now install any missing nodes...
    if (data->scale == NULL) {
	data->scale = new SoScale;
	int lightInd = lightSwitch->findChild(light);
        lightSwitch->insertChild( data->scale, lightInd );
    }
    if (data->scaleInverse == NULL) {
        data->scaleInverse = new SoScale;
	int lightInd = lightSwitch->findChild(light);
        lightSwitch->insertChild( data->scaleInverse, lightInd + 1 );
    }
    if (data->translation == NULL) {
	data->translation = new SoTranslation;
	int scaleInd = lightSwitch->findChild(data->scale);
        lightSwitch->insertChild( data->translation, scaleInd );
    }
    if (data->translationInverse == NULL) {
        data->translationInverse = new SoTranslation;
	int scaleInvInd = lightSwitch->findChild(data->scaleInverse);
        lightSwitch->insertChild( data->translationInverse, scaleInvInd+1 );
    }
    // See if the size was already calculated (this happens when we read 
    // .env files)...
    SbVec3f oldScale = data->scale->scaleFactor.getValue();
    if ( calculatedLightManipSize == FALSE 
	 && oldScale != SbVec3f(1,1,1) ) {
	lightManipSize = oldScale[0];
	calculatedLightManipSize = TRUE;
    }

    data->classPt = this;
    data->colorEditor = NULL;
    data->type = light->getTypeId();
    
    // set the correct label name
    char *str;
    if (data->type.isDerivedFrom( SoDirectionalLight::getClassTypeId()))
	str = Light.directionallight;
    else if (data->type.isDerivedFrom( SoPointLight::getClassTypeId()) )
	str = Light.pointlight;
    else if (data->type.isDerivedFrom( SoSpotLight::getClassTypeId()) )
	str = Light.spotlight;
    else str = "??? ";
    data->name = strdup(str);
    
    // Set the size for the light manips.
    if ( !calculatedLightManipSize )
	calculateLightManipSize();

    data->scale->scaleFactor.setValue( lightManipSize, lightManipSize, 
				       lightManipSize );
    float invSz = (lightManipSize == 0.0) ? 1.0 : 1.0 / lightManipSize;
    data->scaleInverse->scaleFactor.setValue( invSz, invSz, invSz );
    
    //
    // add the menu entry
    //
    addLightMenuEntry(data);
    
    return data;
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	build the light menu entry for the given light.
//
// Use: private
//
void
SoSceneViewer::addLightMenuEntry(SvLightData *data)
//
////////////////////////////////////////////////////////////////////////
{
    //
    // create the motif menu entry
    //
    
    Widget menu = menuItems[SV_LIGHT].widget;
    
    // makes sure menu has been built
    if (menu == NULL)
	return;
    
    // create the submenu widget, adding a callback to update the toggles
    Arg args[8];
    int argnum = 0;
#ifdef MENUS_IN_POPUP
    SoXt::getPopupArgs(XtDisplay(menu), SCREEN(menu), args, &argnum);
#endif
    data->submenuWidget = XmCreatePulldownMenu(menu, "submenu", args, argnum);
    
    XtAddCallback(data->submenuWidget, XmNmapCallback,
	(XtCallbackProc) SoSceneViewer::lightSubmenuDisplay,
	(XtPointer) data);
    
    // create a cascade menu entry which will bring the submenu
    XtSetArg(args[0], XmNsubMenuId, data->submenuWidget);
    data->cascadeWidget = XtCreateWidget(data->name, 
	xmCascadeButtonGadgetClass, menu, args, 1);
    
    // add "on/off" toggle
    data->onOffWidget = XtCreateWidget("On/Off", xmToggleButtonGadgetClass, 
	data->submenuWidget, NULL, 0);
    XtAddCallback(data->onOffWidget, XmNvalueChangedCallback,
	(XtCallbackProc) SoSceneViewer::lightToggleCB, (XtPointer) data);
    
    // add "Icon" toggle
    data->iconWidget = XtCreateWidget("Icon", xmToggleButtonGadgetClass, 
	data->submenuWidget, NULL, 0);
    XtAddCallback(data->iconWidget, XmNvalueChangedCallback,
	(XtCallbackProc) SoSceneViewer::editLightToggleCB, (XtPointer) data);
    
    // add "Edit Color" toggle
    data->editColorWidget = XtCreateWidget("Edit Color", xmPushButtonGadgetClass, 
	data->submenuWidget, NULL, 0);
    XtAddCallback(data->editColorWidget, XmNactivateCallback,
	(XtCallbackProc) SoSceneViewer::editLightColorCB, (XtPointer) data);
    
    // add "Remove" entry
    data->removeWidget = XtCreateWidget("Remove", xmPushButtonGadgetClass, 
	data->submenuWidget, NULL, 0);
    XtAddCallback(data->removeWidget, XmNactivateCallback,
	(XtCallbackProc) SoSceneViewer::removeLightCB, (XtPointer) data);
    
    // manage children
    XtManageChild(data->onOffWidget);
    XtManageChild(data->iconWidget);
    XtManageChild(data->editColorWidget);
    XtManageChild(data->removeWidget);
    XtManageChild(data->cascadeWidget);
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Called by "On/Off" light menu entry when toggle changes.
//
// Use: static private
//
void
SoSceneViewer::lightToggleCB(Widget toggle, SvLightData *data, void *)
//
////////////////////////////////////////////////////////////////////////
{
    data->classPt->turnLightOnOff(data, XmToggleButtonGetState(toggle));
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Turn the given light on or off.
//
// Use: private
//
void
SoSceneViewer::turnLightOnOff(SvLightData *data, SbBool flag)
//
////////////////////////////////////////////////////////////////////////
{
    // check if it is the headlight
    if (data == headlightData)
	setHeadlight( flag );
    else {
	if ( flag )
	    SWITCH_LIGHT_ON(data->lightSwitch);
	else
	    SWITCH_LIGHT_OFF(data->lightSwitch);
    }
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	"Edit" light menu entry callback.
//
// Use: static private
//
void
SoSceneViewer::editLightToggleCB(Widget toggle, SvLightData *data, void *)
//
////////////////////////////////////////////////////////////////////////
{
    data->classPt->editLight( data, XmToggleButtonGetState(toggle) );
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Attach/detach the correct manipulator on the given light.
//
// Use: private
//
void
SoSceneViewer::editLight(SvLightData *data, SbBool flag)
//
////////////////////////////////////////////////////////////////////////
{
    // ??? check if this is for the headlight, which is special cased
    // ??? since a manipulator cannot be used (aligned to camera).
    SbBool forHeadlight = (data == data->classPt->headlightData);

    SoType dataType = data->type;
    SoType dirLightType = SoDirectionalLight::getClassTypeId();
    SoType ptLightType = SoPointLight::getClassTypeId();
    SoType spotLightType = SoSpotLight::getClassTypeId();
    
    //
    // attach the manip to the light and add it to the scene
    //
    if (flag) {

	if (forHeadlight) {

	    if (headlightEditor == NULL) {
		headlightEditor = new SoXtDirectionalLightEditor;
		headlightEditor->setTitle("Headlight Editor");
	    }

	    // Make sure we have the current viewer's headlight
	    SoLight *l = data->classPt->getHeadlight();
	    l->ref();
	    if (data->light)
		data->light->unref();
	    data->light = l;

	    // attach the dir light editor
	    // ??? don't use the path from the root to the headlight 
	    // ??? since we want the light to be relative to the 
	    // ??? camera (i.e. moving the camera shouldn't affect
	    // ??? the arrow in the editor since that direction
	    // ??? is relative to the camera).
	    SoPath *littlePath = new SoPath( data->light );
	    headlightEditor->attach( littlePath );
	    headlightEditor->show();
	}
	else if (data->isManip() == FALSE) {

	    // NOTE: if isManip() == TRUE, then the light is already a manip
	    // and doesn't need to be changed.

	    SoLight *newManip = NULL;
	
	    // allocate the right manipulator type if needed
	    if ( dataType.isDerivedFrom( dirLightType ) ) {
		newManip = new SoDirectionalLightManip;
		newManip->ref();
	    }
	    else if ( dataType.isDerivedFrom( ptLightType ) ) {
		newManip = new SoPointLightManip;
		newManip->ref();
	    }
	    else if ( dataType.isDerivedFrom( spotLightType ) ) {
		newManip = new SoSpotLightManip;
		newManip->ref();
	        // Set dropOffRate non-zero, or it will look like a pointLight.
		((SoSpotLightManip *)newManip)->dropOffRate = .01;
	    }

	    // get the path from the root to the light node
	    SoSearchAction sa;
	    sa.setNode( data->light );
	    sa.apply( currentViewer->getSceneGraph() );
	    SoPath *path = sa.getPath();
	    // ??? light is probably turned off so we don't 
	    // ??? need to print a warning message. Just don't
	    // ??? do anything
	    if (path == NULL) {
		newManip->unref();
		return;
	    }

	    path->ref();

	    // Set the size for the light manips.
	    if ( !calculatedLightManipSize )
		calculateLightManipSize();

	    data->scale->scaleFactor.setValue( lightManipSize, lightManipSize, 
					       lightManipSize );
	    float invSz = (lightManipSize == 0.0) ? 1.0 : 1.0 / lightManipSize;
	    data->scaleInverse->scaleFactor.setValue( invSz, invSz, invSz );
	    
	    // Put the manip into the scene.
	    if ( dataType.isDerivedFrom( ptLightType ) )
		((SoPointLightManip *)newManip)->replaceNode(path);
	    else if (dataType.isDerivedFrom(dirLightType) )
		((SoDirectionalLightManip *)newManip)->replaceNode(path);
	    else if (dataType.isDerivedFrom(spotLightType))
		((SoSpotLightManip *)newManip)->replaceNode(path);

	    // Okay, now that we stuck that manip in there,
	    // we better make a note of it...
	    path->unref();
	    data->light->unref();
	    data->light = newManip;

	}
    }
    //
    // detach the manip from the light and remove it from the scene
    //
    else {
	if (forHeadlight) {
	    // detach editor from light
	    if (headlightEditor != NULL) {
		headlightEditor->detach();
		headlightEditor->hide();
	    }
	}
	else if (data->isManip() == TRUE ) {

	    // replace the lightManip node with a regular light node
	    // get the path from the root to the lightManip node
	    SoSearchAction sa;
	    sa.setNode( data->light );
	    sa.apply( currentViewer->getSceneGraph() );
	    SoPath *path = sa.getPath();

	    if (path != NULL ) {
		path->ref();

		SoLight *newLight;

		if (dataType.isDerivedFrom(ptLightType)) {
		    newLight = new SoPointLight;
		    newLight->ref();
		    ((SoPointLightManip *)data->light)->replaceManip(
					path, (SoPointLight *)newLight );
		}
		else if (dataType.isDerivedFrom(dirLightType)) {
		    // when removing a directional light manip, 
		    // we don't want to lose the translation of the manip.
		    // Since the regular light can't hold this value,
		    // get it from the manip and move it to the translation.

		    transferDirectionalLightLocation(data);

		    newLight = new SoDirectionalLight;
		    newLight->ref();
		    ((SoDirectionalLightManip *)data->light)->replaceManip(
				path, (SoDirectionalLight *)newLight );
		}
		else if (dataType.isDerivedFrom(spotLightType)) {
		    newLight = new SoSpotLight;
		    newLight->ref();
		    ((SoSpotLightManip *)data->light)->replaceManip(
					path, (SoSpotLight *)newLight );
		}
		path->unref();
		data->light->unref();
		data->light = newLight;
	    }
	}
    }
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//     When removing or writing directional light manip, 
//     we don't want to lose the translation of the manip.
//     Since the regular light can't hold this value,
//     get it from the manip and move it to the translation.
//
// Use: private
//
void
SoSceneViewer::transferDirectionalLightLocation( SvLightData *data )
//
////////////////////////////////////////////////////////////////////////
{
    if ( !data->light )
	return;

    if ( !data->light->isOfType(SoDirectionalLightManip::getClassTypeId() ))
	return;

    // when removing a directional light manip, 
    // we don't want to lose the translation of the manip.
    // Since the regular light can't hold this value,
    // get it from the manip and move it to the translation.

    SoDirectionalLightManip *manip 
	= (SoDirectionalLightManip *) data->light;
    SoDirectionalLightDragger *dragger 
	= (SoDirectionalLightDragger *) manip->getDragger();

    SbVec3f lightTrans(0,0,0); 

    if (dragger)
	lightTrans += dragger->translation.getValue();

    SbVec3f scl = data->scale->scaleFactor.getValue();
    lightTrans *= scl[0];

    lightTrans += data->translation->translation.getValue();
    data->translation->translation        = lightTrans;
    data->translationInverse->translation = -lightTrans;

    // Now zero out the translation in the dragger itself:
    dragger->translation = SbVec3f(0,0,0);
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Called by "Edit Color" light menu entry.
//
// Use: static private
//
void
SoSceneViewer::editLightColorCB(Widget, SvLightData *data, void *)
//
////////////////////////////////////////////////////////////////////////
{
    // create the color editor with the right title
    if (data->colorEditor == NULL) {
	data->colorEditor = new MyColorEditor;
	char str[50];
	strcpy(str, data->name);
	strcat(str, " Light Color");
	data->colorEditor->setTitle(str);
    }
    
    if ( !data->colorEditor->isAttached() ) {
	// if this is for the headlight, make sure we have the
	// current viewer headlight
	if (data == data->classPt->headlightData) {
	    SoLight *l = data->classPt->getHeadlight();
	    l->ref();
	    if (data->light)
		data->light->unref();
	    data->light = l;
	}
	
	// normalize the light intensity
	SbColor col;
	col = data->light->color.getValue();
	col *= data->light->intensity.getValue();
	data->light->intensity.setValue( 1.0 );
	data->light->color.setValue( col );
	
	data->colorEditor->attach( &data->light->color, data->light );
    }
    
    data->colorEditor->show();
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	remove button menu entry callback.
//
// Use: static private
//
void
SoSceneViewer::removeLightCB(Widget, SvLightData *data, void *)
//
////////////////////////////////////////////////////////////////////////
{
    data->classPt->removeLight(data);
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	removes the light from the scene, and removes the light data 
//  and pulldown menu entry.
//
// Use: private
//
void
SoSceneViewer::removeLight(SvLightData *data)
//
////////////////////////////////////////////////////////////////////////
{
    // delete the color editor and manip
    delete data->colorEditor;

// note: deleted  code that dealt with the manip.
// Since the light and the manip are one and the same now.
// unrefing the light also removes the manip

    // unref the light (or manip) for this entry
    if (data->light)
	data->light->unref();
    
    // remove the light from the scene
    lightGroup->removeChild( data->lightSwitch );
    
    // nuke the menu entry
    if (data->cascadeWidget != NULL)
	XtDestroyWidget( data->cascadeWidget );
    
    // remove from list and delete the struct
    lightDataList.remove( lightDataList.find(data) );
    delete data;
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//     Calculate the size for the light manips.
//	Called when the first lightmanip is created.
//      Also called when a scene is read or imported, assuming lights
//      have already been created.
//
// Use: private
//
void
SoSceneViewer::calculateLightManipSize()
//
////////////////////////////////////////////////////////////////////////
{
    // Set the size for the light manips.
    // Calculate a good size, based on the size of the scene.
    // Once this size is determined, use it for all other light manips.
    // (We need to save the value because the scene size will change
    //  over time, but we want all light manips to be the same size.
    
    // This routine will also get called again if a new scene is read in.
    
    // Run a bounding box action on the scene...
    SoGetBoundingBoxAction ba(currentViewer->getViewportRegion());
    ba.apply( currentViewer->getSceneGraph() );
    SbBox3f sceneBox = ba.getBoundingBox();
    SbVec3f size;
    if (sceneBox.isEmpty()) {
	// Oh, just take a guess. Default scene would be 2x2x2
	size.setValue(2,2,2);
    }
    else
	size = sceneBox.getMax() - sceneBox.getMin();
//XXX pick a good size!
    lightManipSize = .025 * size.length();

    // Visit every light entry and set the scale and scaleInverse
    // nodes to have the correct lightManipSize.
    for (int i = 0; i < lightDataList.getLength(); i++ ) {
	
	SvLightData *data = (SvLightData *) lightDataList[i];

	if (data->scale != NULL) {
	    if (data->scale->scaleFactor.getValue()[0] != lightManipSize)
		data->scale->scaleFactor.setValue( lightManipSize, 
				    lightManipSize, lightManipSize );
	}
	if (data->scaleInverse != NULL) {
	    float invSz = (lightManipSize == 0.0) ? 1.0 : 1.0 / lightManipSize;
	    if (data->scaleInverse->scaleFactor.getValue()[0] != invSz)
		data->scaleInverse->scaleFactor.setValue( invSz, invSz, invSz );
	}
    }

    calculatedLightManipSize = TRUE;
}


////////////////////////////////////////////////////////////////////////
//
// Description:
//	Called whenever a light submenu is mapped on screen (update 
//  the toggles)
//
// Use: static private
//
void
SoSceneViewer::lightSubmenuDisplay(Widget, SvLightData *data, void *)
//
////////////////////////////////////////////////////////////////////////
{
    SoSceneViewer *sv = data->classPt;
    SbBool set;
    
    //
    // update the "on/off" toggle
    //
    if (data == sv->headlightData)
	set = sv->isHeadlight();
    else
	set = IS_LIGHT_ON(data->lightSwitch);
    if (set)
	TOGGLE_ON(data->onOffWidget);
    else
	TOGGLE_OFF(data->onOffWidget);
    
    //
    // update the "Edit" toggle
    //
    if (data == sv->headlightData)
	set = (sv->headlightEditor != NULL && sv->headlightEditor->isVisible());
    else
	set = (data->isManip() == TRUE );
    if (set)
	TOGGLE_ON(data->iconWidget);
    else
	TOGGLE_OFF(data->iconWidget);
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Called after a paste operation has completed.
//
// Use: static, private
//
void
SoSceneViewer::pasteDoneCB(void *userData, SoPathList *pathList)
//
////////////////////////////////////////////////////////////////////////
{
    SoSceneViewer *sv = (SoSceneViewer *) userData;
    sv->pasteDone(pathList);
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Called after a drop operation has completed.
//
// Use: static, private
//
SbBool
SoSceneViewer::iconDropCB(void *userData, const char *filename)
//
////////////////////////////////////////////////////////////////////////
{
    SoSceneViewer *sv = (SoSceneViewer *) userData;
    sv->fileMode = SV_FILE_IMPORT;
    return sv->doFileIO(filename);
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Called during a drop operation of INVENTOR objects.
//
// Use: static, private
//
SbBool
SoSceneViewer::objDropCB(
    void *userData,
    Atom target,
    void *data, uint32_t numBytes)
//
////////////////////////////////////////////////////////////////////////
{
    SoSceneViewer *sv = (SoSceneViewer *) userData;
    SoPathList *pathList = NULL;
    SbBool success = FALSE;
    Display *d = SoXt::getDisplay();
    	     
    if (data != NULL) {
	if (target == _ATOM_(d, "INVENTOR_2_1") ||
	    target == _ATOM_(d, "VRML_1_0") ||
	    target == _ATOM_(d, "INVENTOR") ||
	    target == _ATOM_(d, "INVENTOR_2_0")) {
	    
	    pathList = SoByteStream::unconvert(data, numBytes);
	    if (pathList != NULL && pathList->getLength() > 0) {
		sv->pasteDone(pathList);
		success = TRUE;
		// pathList will be deleted by pasteDone...
	    }
	}
    }
    
    return success;
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Called after a paste operation has completed, this adds the
// pasted data to our scene graph.
//
// Use: private
//
void
SoSceneViewer::pasteDone(SoPathList *pathList)
//
////////////////////////////////////////////////////////////////////////
{
    if (pathList->getLength() <= 0)
    	return;

    // If this is the only obj, we will view all
    SbBool doViewAll = (selection->getNumChildren() == 0);
    
    // first, detach manips from all selected objects
    detachManipFromAll();
    
    // now, turn off the sel/desel callbacks.
    // we'll turn them on again after we've adjusted the selection
    selection->removeSelectionCallback( SoSceneViewer::selectionCallback, this );
    selection->removeDeselectionCallback( SoSceneViewer::deselectionCallback, this );
    
    // now deselect all, and build up a selection from the pasted paths
    selection->deselectAll();
    
    // Add every path in the path list as a child under selection.
    // Then select each of these paths.
    for (int i = 0; i < pathList->getLength(); i++) {
    
    	// if the head of the path is a selection node, then don't
	// paste the head - rather, paste all of its children. 
	// this makes sure we don't have more than 1 selection node.
	// While we're adding the paths as children, select each path.
    	SoPath *p = (*pathList)[i];
	SoNode *head = p->getHead();
	SoPath *selpath;
	if (head->isOfType(SoSelection::getClassTypeId())) {
	    for (int j = 0; j < ((SoSelection *)head)->getNumChildren(); j++) {
	    	selection->addChild(((SoSelection *)head)->getChild(j));
		
		// create a path from selection to this child
		// and select the path.
		selpath = new SoPath(selection);
		selpath->append(selection->getNumChildren() - 1);
		selection->select(selpath);
	    }
	}
	else {
	    // not a selection node, so just add it.
	    selection->addChild(p->getHead());
	    
	    // create a path from selection to this child
	    // and select the path.
	    selpath = new SoPath(selection);
	    selpath->append(selection->getNumChildren() - 1);
	    selection->select(selpath);
	}
    }
    
    // now add manips to all the selected objects
    attachManipToAll(curManip);
    
    // and turn the sel/desel callbacks back on
    selection->addSelectionCallback( SoSceneViewer::selectionCallback, this );
    selection->addDeselectionCallback( SoSceneViewer::deselectionCallback, this );
    
    // enable/disable keyboard shortcuts
    updateCommandAvailability();
    
    // View all?
    if (doViewAll)
	viewAll();

    delete pathList;
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Build routine for SceneViewer.  This creates all of the X widgets
//
// Use: public, virtual

Widget
SoSceneViewer::buildWidget(Widget parent)
//
////////////////////////////////////////////////////////////////////////
{
    int	    n;
    Arg	    args[10];
    
    // create a form to hold everything together
    SbVec2s size = getSize();
    n = 0;
    if (size[0] != 0 && size[1] != 0) {
	XtSetArg(args[n], XtNwidth, size[0]); n++;
	XtSetArg(args[n], XtNheight, size[1]); n++;
    }
    mgrWidget = XtCreateWidget(getWidgetName(), xmFormWidgetClass, parent, args, n);
    registerWidget(mgrWidget);
    
    // create the topbar menu
    if (showMenuFlag)
	buildAndLayoutMenu(mgrWidget);
    
    // build and layout the current viewer
    whichViewer = SV_VWR_EXAMINER;
    setTitle("SceneViewer (Examiner)");
    currentViewer = viewerList[whichViewer] = new SoXtExaminerViewer(mgrWidget);
    currentViewer->setSceneGraph(sceneGraph);
    currentViewer->setGLRenderAction(highlightRA);
    currentViewer->redrawOnSelectionChange(selection);
    
    setOverlayLogo(currentViewer);
    
    // Fog
    environment->fogColor.setValue( currentViewer->getBackgroundColor() );

    // since we created the camera, do a view all and save this
    // as the starting point (don't want default camera values).
    viewAll();
    saveHomePosition();


    buildAndLayoutViewer(currentViewer);
    
    // manage those children
    if (showMenuFlag)
	XtManageChild(menuWidget);
    currentViewer->show();

    // clipboard is for copy/paste of 3d data.
    //??? what if this SceneViewer had its widget destroyed and rebuilt?
    //??? we need to destroy the clipboards when that happens.
    clipboard = new SoXtClipboard(mgrWidget);
    
    MyDropSite::registerCallback(
	mgrWidget, iconDropCB, objDropCB, this);
    
    return mgrWidget;
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Builds and layout the given viewer.
//
// Use: private
void
SoSceneViewer::buildAndLayoutViewer(SoXtFullViewer *vwr)
//
////////////////////////////////////////////////////////////////////////
{
    if (mgrWidget == NULL)
	return;
    
    // build the viewer if necessary
    if (vwr->getWidget() == NULL) {
	fprintf(stderr, "ERROR - need to create the viewer widget before it can be layed out\n");
	return;
    }
    
    // layout the viewer to be attached under the topbar menu
    // (if the pulldown menu is shown)
    Arg args[12];
    int n = 0;
    if ( showMenuFlag ) {
	XtSetArg(args[n], XmNtopAttachment,	XmATTACH_WIDGET); n++;
	XtSetArg(args[n], XmNtopWidget,		menuWidget); n++;
    }
    else {
	XtSetArg(args[n], XmNtopAttachment,	XmATTACH_FORM); n++;
    }
    XtSetArg(args[n], XmNbottomAttachment,	XmATTACH_FORM); n++;
    XtSetArg(args[n], XmNleftAttachment,	XmATTACH_FORM); n++;
    XtSetArg(args[n], XmNrightAttachment,	XmATTACH_FORM); n++;
    XtSetValues(vwr->getWidget(), args, n);
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Create topbar menu.  Invalid buttons are rendered gray.
//      Each button's callback include a structure with the ID
//      of the button and a pointer to the SoSceneViewer that created
//      it.
//
// Use: private
//
void
SoSceneViewer::buildAndLayoutMenu(Widget parent)
//
////////////////////////////////////////////////////////////////////////
{
    if (menuWidget != NULL)
	return;
    
    Arg			args[8];
    int			i, j, n, id;
    WidgetList		buttons, subButtons;
    int			itemCount, subItemCount;
    WidgetClass	    	widgetClass;
    String  	    	callbackReason;
    XmString		xmstr;
    
    // create topbar menu
    menuWidget = XmCreateMenuBar(parent, "menuBar", NULL, 0);

    Arg popupargs[4];
    int popupn = 0;
#ifdef MENUS_IN_POPUP
    Widget shell = SoXt::getShellWidget(mgrWidget);
    SoXt::getPopupArgs(XtDisplay(menuWidget), SCREEN(shell), popupargs, &popupn);
#endif

    itemCount = XtNumber(pulldownData);
    buttons = (WidgetList) XtMalloc(itemCount * sizeof(Widget));

    for (i = 0; i < itemCount; i++) {
	// Make Topbar menu button
	Widget subMenu = XmCreatePulldownMenu(menuWidget, "subMenu", popupargs, popupn);
	
#ifdef MENUS_IN_POPUP
	// register callbacks to load/unload the pulldown colormap when the
	// pulldown menu is posted.
	SoXt::registerColormapLoad(subMenu, shell);
#endif
	
	id = pulldownData[i].id;
	menuItems[id].widget = subMenu;
    	XtAddCallback(subMenu, XmNmapCallback,
	    (XtCallbackProc) SoSceneViewer::menuDisplay,
	    (XtPointer) &menuItems[id]);

    	XtSetArg(args[0], XmNsubMenuId, subMenu);
	buttons[i] = XtCreateWidget(pulldownData[i].name,
	    xmCascadeButtonGadgetClass, menuWidget, args, 1);

	// Make subMenu buttons
	subItemCount = pulldownData[i].subItemCount;
	subButtons = (WidgetList) XtMalloc(subItemCount * sizeof(Widget));
	
	for (j = 0; j < subItemCount; j++) {
	    if (pulldownData[i].subMenu[j].buttonType == SV_SEPARATOR)
		subButtons[j] = XtCreateWidget(NULL, xmSeparatorGadgetClass, 
		    subMenu, NULL, 0);
	    else {
    	    	switch (pulldownData[i].subMenu[j].buttonType) {
		    case SV_PUSH_BUTTON:
			widgetClass = xmPushButtonGadgetClass;
			callbackReason = XmNactivateCallback;
			n = 0;
		    	break;
		    case SV_TOGGLE_BUTTON:
			widgetClass = xmToggleButtonGadgetClass;
			callbackReason = XmNvalueChangedCallback;
			n = 0;
		    	break;
		    case SV_RADIO_BUTTON:
			widgetClass = xmToggleButtonGadgetClass;
			callbackReason = XmNvalueChangedCallback;
			XtSetArg(args[0], XmNindicatorType, XmONE_OF_MANY);
			n = 1;
		    	break;
		    default:
			fprintf(stderr, "SceneViewer INTERNAL ERROR: bad buttonType\n");
		    	break;
		}
		
		// check for keyboard accelerator
		char *accel = pulldownData[i].subMenu[j].accelerator;
		char *accelText = pulldownData[i].subMenu[j].accelText;
		xmstr = NULL;
		if (accel != NULL) {
		    XtSetArg(args[n], XmNaccelerator, accel); n++;
		    
		    if (accelText != NULL) {
			xmstr = XmStringCreate(accelText,
					 XmSTRING_DEFAULT_CHARSET);
			XtSetArg(args[n], XmNacceleratorText, xmstr); n++;
		    }
		}
		
		subButtons[j] = XtCreateWidget(
		    pulldownData[i].subMenu[j].name,
		    widgetClass,
		    subMenu, args, n);
		
		if (xmstr != NULL)
		    XmStringFree(xmstr);
		id = pulldownData[i].subMenu[j].id;
		menuItems[id].widget = subButtons[j];
		XtAddCallback(subButtons[j], callbackReason,
		    (XtCallbackProc)SoSceneViewer::processTopbarEvent,
		    (XtPointer) &menuItems[id]);
	    }
	}
	XtManageChildren(subButtons, subItemCount);
	XtFree((char *)subButtons);
    }
    XtManageChildren(buttons, itemCount);
    XtFree((char *)buttons);
    
    //
    // layout the menu bar
    //
    n = 0;
    XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); n++;
    XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); n++;
    XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); n++;
    XtSetValues(menuWidget, args, n);
    
    //
    // Add the light items which are dynamically created
    //    
    // first add the headlight
    addLightMenuEntry(headlightData);
    XtUnmanageChild(headlightData->removeWidget);
    XtUnmanageChild(headlightData->editColorWidget);
    xmstr = XmStringCreate( Light.editlight, XmSTRING_DEFAULT_CHARSET);
    XtSetArg(args[0], XmNlabelString, xmstr);
    XtSetValues(headlightData->iconWidget, args, 1);
    XmStringFree(xmstr);
    
    // now the regular lights
    for (i=0; i < lightDataList.getLength(); i++)
	addLightMenuEntry( (SvLightData *) lightDataList[i] );
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Show/hide the pulldown menu bar.
//
// Use: public
void
SoSceneViewer::showMenu(SbBool flag)
//
////////////////////////////////////////////////////////////////////////
{
    if (showMenuFlag == flag || mgrWidget == NULL) {
	showMenuFlag = flag;
	return;
    }
    
    showMenuFlag = flag;
    
    if ( showMenuFlag ) {
	
	// turn topbar menu on
	if (menuWidget == NULL)
	    buildAndLayoutMenu(mgrWidget);
	XtManageChild(menuWidget);
    	
	// attach viewer to bottom of menu
	Arg args[2];
	int n = 0;
	XtSetArg(args[n], XmNtopAttachment,	XmATTACH_WIDGET); n++;
	XtSetArg(args[n], XmNtopWidget,		menuWidget);    n++;
	XtSetValues(currentViewer->getWidget(), args, n);
    }
    else {
	// attach viewer to form
	Arg args[2];
	int n = 0;
	XtSetArg(args[n], XmNtopAttachment,	XmATTACH_FORM); n++;
	XtSetValues(currentViewer->getWidget(), args, n);
    	
	// turn topbar menu off
	if (menuWidget != NULL)
	    XtUnmanageChild(menuWidget);
    }
}

////////////////////////////////////////////////////////////////////////
//
//  Manage the changes in the selected node(s)
//
//  Use: private, static
//
SoPath *
SoSceneViewer::pickFilterCB(void *userData, const SoPickedPoint *pick)
//
////////////////////////////////////////////////////////////////////////
{
    SoSceneViewer *sv = (SoSceneViewer *) userData;
    SoPath *filteredPath = NULL;
    
    // If there are any transform manips along the path, check if they
    // belong to our personal set of manips. 
    // If so, change the path so it points to the object the manip
    // is attached to.
    SoFullPath *fullP = (SoFullPath *) pick->getPath();
    SoNode     *n;
    for (int i = 0; i < fullP->getLength(); i++ ) {
	n = fullP->getNode(i);
	if (n->isOfType(SoTransformManip::getClassTypeId())) {
	    int which = sv->maniplist->find((SoTransformManip *) n);
	    if (which != -1) {
		filteredPath = sv->maniplist->getSelectionPath(which);
		return filteredPath;
	    }
	}
    }

    // If we didn't pick one of our manipulators, then return the pickPath
    filteredPath = pick->getPath();
    return filteredPath;
}

////////////////////////////////////////////////////////////////////////
//
//  Manage the changes in the selected node(s)
//
//  Use: private, static
//
void
SoSceneViewer::deselectionCallback( void *userData,	   	     // my data
				    SoPath *deselectedPath ) // object
//
////////////////////////////////////////////////////////////////////////
{
    SoSceneViewer *sv = (SoSceneViewer *) userData;

    // remove the manip
    sv->detachManip( deselectedPath );
    
    // Remove editors
    if (sv->materialEditor)
	sv->materialEditor->detach();
    
    if (sv->colorEditor)
    	sv->colorEditor->detach();

    if (sv->transformSliderSet)
	sv->transformSliderSet->setNode( NULL );

    // enable/disable cmd key shortcuts and menu items
    sv->updateCommandAvailability();
}

////////////////////////////////////////////////////////////////////////
//
//  Manage the changes in the selected node(s)
//
//  Use: private, static
//
void
SoSceneViewer::selectionCallback( void *userData,		 // my data
				  SoPath *selectedPath ) // object
//
////////////////////////////////////////////////////////////////////////
{
    SoSceneViewer *sv = (SoSceneViewer *) userData;

    // attach the manip
    sv->attachManip( sv->curManip, selectedPath );

    //
    // If active, attach editors to new selection.
    //
    SoMaterial *mtl = NULL;
    if ( sv->materialEditor && sv->materialEditor->isVisible()) {
	mtl = sv->findMaterialForAttach(selectedPath);
	sv->materialEditor->attach(mtl);
    }
    
    if (sv->colorEditor && sv->colorEditor->isVisible()) {
    	if (mtl == NULL)
	    mtl = sv->findMaterialForAttach(selectedPath);
    	sv->colorEditor->attach(&(mtl->diffuseColor), 0, mtl);
    }
    
    if ( sv->transformSliderSet && sv->transformSliderSet->isVisible() ) {
	SoPath      *editTransformPath;
	editTransformPath = sv->findTransformForAttach( selectedPath );
	if ( editTransformPath == NULL ) {
	    sv->transformSliderSet->setNode( NULL );
	}
	else  {
	    editTransformPath->ref();
	    sv->transformSliderSet->setNode(((SoFullPath *)editTransformPath)->getTail() );
	    editTransformPath->unref();
	}
    }

    // enable/disable cmd key shortcuts and menu items
    sv->updateCommandAvailability();
}

////////////////////////////////////////////////////////////////////////
//
//  Remove selected objects from the scene graph. 
//  In this demo, we don't really know how the graphs are set up,
//  so act conservatively, and simply remove the node which is the
//  tail of the path from its parent. Note if the node is instanced,
//  all instances will be destroyed. Then travel up the path to a
//  parent separator. If there are no other shapes under the separator,
//  destroy it too.
//
//  Other applications might delete selected objects a different way,
//  depending on how the data is organized in the scene graph.
//
//  Use: protected
//
void
SoSceneViewer::destroySelectedObjects()
//
////////////////////////////////////////////////////////////////////////
{
    for (int i = selection->getNumSelected() - 1; i >= 0; i--) {
	SoPath *p = (*selection)[i];
	p->ref();
	
	// Deselect this path
	selection->deselect(i);

	// Remove the tail node from the graph
	SoGroup *g = (SoGroup *) p->getNodeFromTail(1);
	g->removeChild(p->getTail());
	
	// Travel up the path to separators, and see if this was
	// the only shape node under the sep. If so, delete the sep too.
	// (Don't go all the way up to the selection node).
	SbBool shapeFound = FALSE;
	int j = 0;
	while ((! shapeFound) && (j < p->getLength() - 1)) {
	    SoNode *n = p->getNodeFromTail(j);
	    if (n->isOfType(SoSeparator::getClassTypeId())) {
		// Search for other shape nodes
		SoSearchAction sa;
		sa.setFind(SoSearchAction::TYPE);
		sa.setType(SoShape::getClassTypeId());
		sa.apply(n);
		
		// If no other shapes under this separator, delete it!
		if (sa.getPath() == NULL) {
		    g = (SoGroup *) p->getNodeFromTail(j + 1);
		    g->removeChild(n);
		    
		    // Reset j since we have a new end of path
		    j = 0;
		}
		else shapeFound = TRUE;
	    }
	    // Else a group with no children?
	    else if (n->isOfType(SoGroup::getClassTypeId()) &&
		(((SoGroup *)n)->getNumChildren() == 0)) {
		    g = (SoGroup *) p->getNodeFromTail(j + 1);
		    g->removeChild(n);
		    
		    // Reset j since we have a new end of path
		    j = 0;
	    }
	    // Else continue up the path looking for separators
	    else j++;
	}
	
	p->unref();
    }
}

////////////////////////////////////////////////////////////////////////
//
//  This enables/disables cmd key shortcuts and menu items
//  based on whether there are any objects, and/or any selected objects
//  in the scene graph.
//
//  Use: static private
//
// 
void
SoSceneViewer::updateCommandAvailability()
//
////////////////////////////////////////////////////////////////////////
{
    Arg args[1];

    // enable/disable based on the number of child objects in scene
    if (selection->getNumChildren() == 0)
	 XtSetArg(args[0], XmNsensitive, False);
    else XtSetArg(args[0], XmNsensitive, True);
    
    // save (if no children, nothing to save)
    XtSetValues(menuItems[SV_FILE_SAVE].widget, args, 1);
    XtSetValues(menuItems[SV_FILE_SAVE_AS].widget, args, 1);
    
    // pickAll (if no children, nothing to pick)
    XtSetValues(menuItems[SV_EDIT_PICK_ALL].widget, args, 1);


    // enable/disable based on the number of selected objects
    if (selection->getNumSelected() == 0)
	 XtSetArg(args[0], XmNsensitive, False);
    else XtSetArg(args[0], XmNsensitive, True);
    
    // if nothing selected, then cannot pick parent, cut, copy, delete,
    // view selection, bring up editors
    XtSetValues(menuItems[SV_EDIT_PICK_PARENT].widget, args, 1);
    XtSetValues(menuItems[SV_EDIT_CUT].widget, args, 1);
    XtSetValues(menuItems[SV_EDIT_COPY].widget, args, 1);
    XtSetValues(menuItems[SV_EDIT_DELETE].widget, args, 1);
    XtSetValues(menuItems[SV_VIEW_SELECTION].widget, args, 1);
    XtSetValues(menuItems[SV_EDITOR_TRANSFORM].widget, args, 1);
    XtSetValues(menuItems[SV_EDITOR_MATERIAL].widget, args, 1);
    XtSetValues(menuItems[SV_EDITOR_COLOR].widget, args, 1);
}

////////////////////////////////////////////////////////////////////////
//
//  Called by Xt when a menu is about to be displayed.
//  This gives us a chance to update any items in the menu.
//
//  Use: static private
//
void
SoSceneViewer::menuDisplay(Widget, SoSceneViewerData *data, XtPointer)
//
////////////////////////////////////////////////////////////////////////
{
    SoSceneViewer *sv = data->classPt;
    Arg args[1];
    char str[100];
    XmString xmstr;
    
    switch (data->id) {
	case SV_FILE:
	    // disable saving if there isn't any geometry
	    if (sv->selection->getNumChildren() == 0)
	    	XtSetArg(args[0], XmNsensitive, False);
	    else 
	    	XtSetArg(args[0], XmNsensitive, True);
	    
	    XtSetValues(sv->menuItems[SV_FILE_SAVE].widget, args, 1);
	    XtSetValues(sv->menuItems[SV_FILE_SAVE_AS].widget, args, 1);
	    
	    // update the "Save" menu entry to reflect the current file name
#ifndef EXPLORER 
	    strcpy(str,fileData[5].name );
#else
	    strcpy(str,fileData[0].name );
#endif
	    if (sv->fileName != NULL) {
		// get the file name withought the entire path
		char *pt = strrchr(sv->fileName, '/');   // last occurance of '/'
		pt = (pt == NULL) ? sv->fileName : pt + 1;
		strcat(str, " -> ");
		strcat(str, pt);
	    }
	    xmstr = XmStringCreate(str, XmSTRING_DEFAULT_CHARSET);
	    XtSetArg(args[0], XmNlabelString, xmstr);
	    XtSetValues(sv->menuItems[SV_FILE_SAVE].widget, args, 1);
	    XmStringFree(xmstr);
	    break;
	    
#ifndef EXPLORER
    	case SV_EDIT:
	    // disable cut, copy, delete, pickParent if there is no selection
	    if(sv->selection->getNumSelected() == 0)
	    	XtSetArg(args[0], XmNsensitive, False);
	    else 
	    	XtSetArg(args[0], XmNsensitive, True);
	    
	    XtSetValues(sv->menuItems[SV_EDIT_PICK_PARENT].widget, args, 1);
	    XtSetValues(sv->menuItems[SV_EDIT_CUT].widget, args, 1);
	    XtSetValues(sv->menuItems[SV_EDIT_COPY].widget, args, 1);
	    XtSetValues(sv->menuItems[SV_EDIT_DELETE].widget, args, 1);
	    
	    // disable pick all if there are nothing to pick
	    if (sv->selection->getNumChildren() == 0)
	    	XtSetArg(args[0], XmNsensitive, False);
	    else 
	    	XtSetArg(args[0], XmNsensitive, True);
	    XtSetValues(sv->menuItems[SV_EDIT_PICK_ALL].widget, args, 1);
	    break;
#endif /* EXPLORER */
	    
	case SV_VIEW:
	    // set pick/edit toggle
	    if ( sv->isViewing() )
		 TOGGLE_OFF(sv->menuItems[SV_VIEW_PICK].widget);
	    else TOGGLE_ON(sv->menuItems[SV_VIEW_PICK].widget);
	    
#ifdef EXPLORER
	    // set user pick toggle
	    if ( sv->userModeFlag )
		 TOGGLE_ON(sv->menuItems[SV_VIEW_USER].widget);
	    else TOGGLE_OFF(sv->menuItems[SV_VIEW_USER].widget);
#endif
	    // Set the correct viewer
	    TOGGLE_OFF(sv->menuItems[SV_VIEW_EXAMINER].widget);
	    TOGGLE_OFF(sv->menuItems[SV_VIEW_WALK].widget);
	    TOGGLE_OFF(sv->menuItems[SV_VIEW_PLANE].widget);
	    TOGGLE_OFF(sv->menuItems[SV_VIEW_FLY].widget);
	    switch ( sv->whichViewer ) {
		case SV_VWR_EXAMINER:
		    TOGGLE_ON(sv->menuItems[SV_VIEW_EXAMINER].widget);
		    break;
		case SV_VWR_WALK:
		    TOGGLE_ON(sv->menuItems[SV_VIEW_WALK].widget);
		    break;
		case SV_VWR_FLY:
		    TOGGLE_ON(sv->menuItems[SV_VIEW_FLY].widget);
		    break;
		case SV_VWR_PLANE:
		    TOGGLE_ON(sv->menuItems[SV_VIEW_PLANE].widget);
		    break;
	    }
	    
	    // set the correct transparency type
	    TOGGLE_OFF(sv->menuItems[SV_VIEW_SCREEN_TRANSPARENCY].widget);
	    TOGGLE_OFF(sv->menuItems[SV_VIEW_BLEND_TRANSPARENCY].widget);
	    TOGGLE_OFF(sv->menuItems[SV_VIEW_DELAY_BLEND_TRANSPARENCY].widget);
	    TOGGLE_OFF(sv->menuItems[SV_VIEW_SORT_BLEND_TRANSPARENCY].widget);
	    switch( sv->getTransparencyType() ) {
		case SoGLRenderAction::SCREEN_DOOR:
		    TOGGLE_ON(sv->menuItems[SV_VIEW_SCREEN_TRANSPARENCY].widget);
		    break;
		case SoGLRenderAction::BLEND:
		    TOGGLE_ON(sv->menuItems[SV_VIEW_BLEND_TRANSPARENCY].widget);
		    break;
		case SoGLRenderAction::DELAYED_BLEND:
		    TOGGLE_ON(sv->menuItems[SV_VIEW_DELAY_BLEND_TRANSPARENCY].widget);
		    break;
		case SoGLRenderAction::SORTED_OBJECT_BLEND:
		    TOGGLE_ON(sv->menuItems[SV_VIEW_SORT_BLEND_TRANSPARENCY].widget);
		    break;
	    }
	    
	    // disable view selection if nothing is selected
	    if ( sv->selection->getNumSelected() == 0 )
	    	XtSetArg(args[0], XmNsensitive, False);
	    else 
	    	XtSetArg(args[0], XmNsensitive, True);
	    XtSetValues(sv->menuItems[SV_VIEW_SELECTION].widget, args, 1);
	    
	    // set fog toggle
	    if ( sv->fogFlag )
		 TOGGLE_ON(sv->menuItems[SV_VIEW_FOG].widget);
	    else TOGGLE_OFF(sv->menuItems[SV_VIEW_FOG].widget);
	    
	    // set antialiasing toggle
	    if ( sv->antialiasingFlag )
		 TOGGLE_ON(sv->menuItems[SV_VIEW_ANTIALIASING].widget);
	    else TOGGLE_OFF(sv->menuItems[SV_VIEW_ANTIALIASING].widget);
	    
	    break;
	    
#ifndef EXPLORER
    	case SV_SELECTION:
	    // mirror the selection policy
	    TOGGLE_OFF(sv->menuItems[SV_SEL_SINGLE_SELECT].widget);
	    TOGGLE_OFF(sv->menuItems[SV_SEL_TOGGLE_SELECT].widget);
	    TOGGLE_OFF(sv->menuItems[SV_SEL_SHIFT_SELECT].widget);
	    switch ( sv->selection->policy.getValue() ) {
		case SoSelection::SINGLE:
		    TOGGLE_ON (sv->menuItems[SV_SEL_SINGLE_SELECT].widget);
		    break;
	    	case SoSelection::TOGGLE:
		    TOGGLE_ON (sv->menuItems[SV_SEL_TOGGLE_SELECT].widget);
		    break;
	    	case SoSelection::SHIFT:
		    TOGGLE_ON (sv->menuItems[SV_SEL_SHIFT_SELECT].widget);
		    break;
		default:
		    fprintf(stderr, "INTERNAL ERROR, unknown selection policy\n");
		    break;
	    }
		
	    break;
#endif /* EXPLORER */
	    
    	case SV_EDITOR:
	    // disable items if there is no selection
	    if(sv->selection->getNumSelected() == 0)
	    	XtSetArg(args[0], XmNsensitive, False);
	    else 
	    	XtSetArg(args[0], XmNsensitive, True);
	    
	    XtSetValues(sv->menuItems[SV_EDITOR_TRANSFORM].widget, args, 1);
	    XtSetValues(sv->menuItems[SV_EDITOR_MATERIAL].widget, args, 1);
	    XtSetValues(sv->menuItems[SV_EDITOR_COLOR].widget, args, 1);
	    break;
	    
   	case SV_MANIP:

	    // First, the section with the different types of manipulators.
	    TOGGLE_OFF( sv->menuItems[SV_MANIP_HANDLEBOX].widget );
	    TOGGLE_OFF( sv->menuItems[SV_MANIP_TRANSFORMER].widget );
	    TOGGLE_OFF( sv->menuItems[SV_MANIP_TRACKBALL].widget );
	    TOGGLE_OFF( sv->menuItems[SV_MANIP_JACK].widget );
	    TOGGLE_OFF( sv->menuItems[SV_MANIP_CENTERBALL].widget );
	    TOGGLE_OFF( sv->menuItems[SV_MANIP_XFBOX].widget );
	    TOGGLE_OFF( sv->menuItems[SV_MANIP_TABBOX].widget );
	    TOGGLE_OFF( sv->menuItems[SV_MANIP_NONE].widget );
	    
	    // Turn appropriate radio button on
	    if (sv->curManip == SV_HANDLEBOX)
		TOGGLE_ON(sv->menuItems[SV_MANIP_HANDLEBOX].widget);
	    else if (sv->curManip == SV_TRACKBALL)
		TOGGLE_ON(sv->menuItems[SV_MANIP_TRACKBALL].widget);
	    else if (sv->curManip == SV_TRANSFORMER)
		TOGGLE_ON(sv->menuItems[SV_MANIP_TRANSFORMER].widget);
	    else if (sv->curManip == SV_JACK)
		TOGGLE_ON(sv->menuItems[SV_MANIP_JACK].widget);
	    else if (sv->curManip == SV_CENTERBALL)
		TOGGLE_ON(sv->menuItems[SV_MANIP_CENTERBALL].widget);
	    else if (sv->curManip == SV_XFBOX)
		TOGGLE_ON(sv->menuItems[SV_MANIP_XFBOX].widget);
	    else if (sv->curManip == SV_TABBOX)
		TOGGLE_ON(sv->menuItems[SV_MANIP_TABBOX].widget);
	    else 
		TOGGLE_ON(sv->menuItems[SV_MANIP_NONE].widget);

	    // Next, the toggle that says whether we replace current 
	    // manipulators every time we change the type given in the menu.
	    if (sv->curManipReplaces == TRUE ) 
		TOGGLE_ON(  sv->menuItems[SV_MANIP_REPLACE_ALL].widget );
	    else
		TOGGLE_OFF( sv->menuItems[SV_MANIP_REPLACE_ALL].widget );

	    break;
	    
	case SV_LIGHT:
	    // disable the add light entries if we have more than 8 lights
	    if (sv->lightDataList.getLength() < 8)
	    	XtSetArg(args[0], XmNsensitive, True);
	    else 
	    	XtSetArg(args[0], XmNsensitive, False);
	    
	    XtSetValues(sv->menuItems[SV_LIGHT_ADD_DIRECT].widget, args, 1);
	    XtSetValues(sv->menuItems[SV_LIGHT_ADD_POINT].widget, args, 1);
	    XtSetValues(sv->menuItems[SV_LIGHT_ADD_SPOT].widget, args, 1);
	    
	    // update the headlight label (show on/off with '*')
	    sv->isHeadlight() ? strcpy(str, "* ") : strcpy(str, "  ");
	    strcat(str, sv->headlightData->name);
	    xmstr = XmStringCreate(str, XmSTRING_DEFAULT_CHARSET);
	    XtSetArg(args[0], XmNlabelString, xmstr);
	    XtSetValues(sv->headlightData->cascadeWidget, args, 1);
	    XmStringFree(xmstr);
	    
	    // update the lights label (show on/off with '*')
	    {
		for (int i=0; i < sv->lightDataList.getLength(); i++) {
		    SvLightData *data = (SvLightData *) sv->lightDataList[i];
		    IS_LIGHT_ON(data->lightSwitch) ? strcpy(str, "* ") : strcpy(str, "  ");
		    strcat(str, data->name);
		    xmstr = XmStringCreate(str, XmSTRING_DEFAULT_CHARSET);
		    XtSetArg(args[0], XmNlabelString, xmstr);
		    XtSetValues(data->cascadeWidget, args, 1);
		    XmStringFree(xmstr);
		}
	    }
	    break;
	    
	default:
	    break;
    }
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Determines whether a given node is affected by a transform.
//
// Use: static, public
//
SbBool
SoSceneViewer::isAffectedByTransform(
	SoNode *theNode )		// node to be affected?
//
////////////////////////////////////////////////////////////////////////
{
    if ( theNode->isOfType( SoGroup::getClassTypeId() )
	    || theNode->isOfType( SoShape::getClassTypeId() )
	    || theNode->isOfType( SoCamera::getClassTypeId() )
	    || theNode->isOfType( SoLight::getClassTypeId() ) )  {
	return TRUE;
    }
    return FALSE;
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Determines whether a given node is affected by material node.
//
// Use: static, public
//
SbBool
SoSceneViewer::isAffectedByMaterial(
	SoNode *theNode )		// node to be affected?
//
////////////////////////////////////////////////////////////////////////
{
    if ( theNode->isOfType( SoGroup::getClassTypeId() )
	    || theNode->isOfType( SoShape::getClassTypeId() ) ) {
	return TRUE;
    }
    return FALSE;
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Create the lights and camera environment structure.
//
// Use: private
//
void
SoSceneViewer::createLightsCameraEnvironment()
//
////////////////////////////////////////////////////////////////////////
{
    // Group {
    //	  Label { "SoSceneViewer Environment v3.0" }
    //    Camera {}
    //    Environment {}
    //    Group {
    //        Switch { Light 1 }    	# switch is child 0, light is child 0
    //        Switch { Light 2 }    	# switch is child 1, light is child 0
    //        ...
    //    }
    // }
    //
    // NOTE: since the camera may be switched by the viewer (ortho/perspective toggle)
    // make sure to get the camera from the viewer (and not cache the camera).
    
    lightsCameraEnvironment = new SoGroup;
    environment     	    = new SoEnvironment;
    lightGroup 	    	    = new SoGroup;
    envLabel	  	    = new SoLabel;

    envLabel->label.setValue(SV_ENV_LABEL);
    lightsCameraEnvironment->addChild(envLabel);
#ifndef EXPLORER
    // Explorer SceneViewer doesn't remove cameras from the Scene, so
    // don't add any...
    lightsCameraEnvironment->addChild(new SoPerspectiveCamera);
#endif
    lightsCameraEnvironment->addChild(environment);
    lightsCameraEnvironment->addChild(lightGroup);
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//	Brings up the "About..." dialog (same code as gavin demo programs)
//
// Use: private
//
void
SoSceneViewer::showAboutDialog()
//
////////////////////////////////////////////////////////////////////////
{
    if (access(IVDEMOBINDIR "/SceneViewer.about", R_OK) != 0)
    {
	system("xmessage 'Sorry, could not find "
	       IVDEMOBINDIR "/SceneViewer.about' > /dev/null");
	return;
    }

    char command[100];
    sprintf(command, "which " PDFVIEWER " > /dev/null");

    int err = system(command);
    if (err)
    {
	system("xmessage 'You must install " PDFVIEWER
	       " for this function to work' > /dev/null");
	return;
    }

    sprintf(command, PDFVIEWER " "
            IVDEMOBINDIR "/SceneViewer.about &");
    system(command);
}

//
// define those generic virtual functions
//
const char *
SoSceneViewer::getDefaultWidgetName() const
{ return "SoSceneViewer"; }

const char *
SoSceneViewer::getDefaultTitle() const
{ return "SceneViewer"; }

const char *
SoSceneViewer::getDefaultIconTitle() const
{ return "SceneViewer"; }