[go: up one dir, main page]

File: SoField.cpp

package info (click to toggle)
coin3 3.1.3-1
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 48,344 kB
  • ctags: 70,042
  • sloc: cpp: 314,328; ansic: 15,927; sh: 13,635; makefile: 8,780; perl: 2,149; lex: 1,302; lisp: 1,247; yacc: 184; xml: 175; sed: 68
file content (2637 lines) | stat: -rw-r--r-- 81,621 bytes parent folder | download | duplicates (2)
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
/**************************************************************************\
 *
 *  This file is part of the Coin 3D visualization library.
 *  Copyright (C) by Kongsberg Oil & Gas Technologies.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  ("GPL") version 2 as published by the Free Software Foundation.
 *  See the file LICENSE.GPL at the root directory of this source
 *  distribution for additional information about the GNU GPL.
 *
 *  For using Coin with software that can not be combined with the GNU
 *  GPL, and for taking advantage of the additional benefits of our
 *  support services, please contact Kongsberg Oil & Gas Technologies
 *  about acquiring a Coin Professional Edition License.
 *
 *  See http://www.coin3d.org/ for more information.
 *
 *  Kongsberg Oil & Gas Technologies, Bygdoy Alle 5, 0257 Oslo, NORWAY.
 *  http://www.sim.no/  sales@sim.no  coin-support@coin3d.org
 *
\**************************************************************************/

/*!
  \class SoField SoField.h Inventor/fields/SoField.h
  \brief The SoField class is the top-level abstract base class for fields.
  \ingroup fields

  Fields is the mechanism used throughout Coin for encapsulating basic
  data types to detect changes made to them, and to provide
  conversion, import and export facilities.

  Almost all public properties in nodes are stored in fields, and so
  are the inputs and outputs of engines. So fields can be viewed as
  the major mechanism for scenegraph nodes and engines to expose their
  public API.

  Forcing data modification to go through a public function interface
  while hiding the data members makes it possible to automatically
  detect and react upon changes in the data structures set up by the
  application programmer.

  E.g. the default behavior when changing the value of a field in a
  scenegraph node is that there'll automatically be a chain of
  notifications -- from the field to the owner node, from that node to
  it's parent node, etc all the way through to the top-most root node,
  where the need for a rendering update will be signalled to the
  application.

  (This notification mechanism is the underlying feature that makes the
  Coin library classify as a so-called \e data-driven scenegraph API.

  The practical consequences of this is that rendering and many other
  processing actions is default scheduled to \e only happen when
  something has changed in the retained data structures, making the
  Coin library under normal circumstances \e much less CPU intensive
  than so-called "application-driven" scenegraph API, like for
  instance SGI IRIS Performer, which are continuously re-rendering
  even when nothing has changed in the data structures or with the
  camera viewport.)

  Storing data members as fields also provides other conveniences for
  the application programmer:

  \li Fields can be connected to other fields. This makes it for
      instance possible to have "self-updating" scenes, ie you can set
      up scenes where entities \e automatically react to changes in
      other entities. This also provides a necessary mechanism for
      having "auto-animating" scenes, as it is possible to connect any
      field to the global field named \c realTime, providing a
      wall-clock timer.

  \li When connecting fields to each other, Coin has built-in
      mechanisms for automatically converting between different field
      types.

  \li Fields provide persistance for scenegraph import (and export)
      operations. This includes animating entities, so animations can
      be stored within ordinary Inventor format files.

  \li Fields provides features for introspection: they have a
      type-system, just like for nodes and actions, they are named,
      and it is also possible to find out which node, engine or other
      entity owns a field.

  \li Fields can hold multiple values. Multi-value fields comes with a
      much higher level interface abstraction than standard C/C++
      arrays.

  Note: there are some field classes which has been obsoleted from the
  Open Inventor API. They are: SoSFLong, SoSFULong, SoMFLong and
  SoMFULong. You should use these classes instead (respectively):
  SoSFInt32, SoSFUInt32, SoMFInt32 and SoMFUInt32.

  \TOOLMAKER_REF

  \sa SoFieldContainer, SoFieldData
*/

#include <Inventor/fields/SoField.h>

#include <cassert>
#include <cstring>

#include <Inventor/fields/SoFields.h>

#include <Inventor/SoDB.h>
#include <Inventor/SoInput.h>
#include <Inventor/SoOutput.h>
#include <Inventor/actions/SoWriteAction.h>
#include <Inventor/engines/SoNodeEngine.h>
#include <Inventor/errors/SoDebugError.h>
#include <Inventor/errors/SoReadError.h>
#include <Inventor/lists/SoEngineList.h>
#include <Inventor/lists/SoEngineOutputList.h>
#include <Inventor/misc/SoProtoInstance.h>
#include <Inventor/nodes/SoNode.h>
#include <Inventor/sensors/SoDataSensor.h>

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H
#include "engines/SoConvertAll.h"
#include "fields/SoGlobalField.h"
#include "SbBasicP.h"
#include "tidbitsp.h"
#include "threads/threadsutilp.h"
#include "io/SoWriterefCounter.h"
inline unsigned int SbHashFunc(const void * key);
#include "misc/SbHash.h"
inline unsigned int SbHashFunc(const void * key)
{
  return SbHashFunc(reinterpret_cast<size_t>(key));
}
#include "coindefs.h" // COIN_STUB()

#ifdef COIN_THREADSAFE
#include "threads/recmutexp.h"
#define SOFIELD_RECLOCK (void) cc_recmutex_internal_field_lock()
#define SOFIELD_RECUNLOCK (void) cc_recmutex_internal_field_unlock()

#else // COIN_THREADSAFE

#define SOFIELD_RECLOCK
#define SOFIELD_RECUNLOCK

#endif // !COIN_THREADSAFE

static const int SOFIELD_GET_STACKBUFFER_SIZE = 1024;
// need one static mutex for field_buffer in SoField::get(SbString &)
static void * sofield_mutex = NULL;

// flags for this->statusbits

static const char IGNOREDCHAR = '~';
static const char CONNECTIONCHAR = '=';
/*
  This class is used to aid in "multiplexing" the pointer member of
  SoField. This is a way to achieve the goal of using minimum storage
  space for SoField classes in the default case (which is important,
  as fields are ubiquitous in Coin). The default case means no
  connections and only a field container given. If any connections are
  made (either "to" or "from"), we allocate an SoConnectStorage and
  move the field container pointer into it, while swapping in the
  SoConnectStorage pointer where the field container pointer used to
  be.
*/
class SoConnectStorage {
public:
  SoConnectStorage(SoFieldContainer * c, SoType t)
    : container(c),
    lastnotify(NULL),
    fieldtype(t),
    maptoconverter(13) // save about ~1kB vs default nr of buckets
    {
    }

#if COIN_DEBUG
  // Check that everything has been emptied.
  ~SoConnectStorage()
  {
    assert(this->maptoconverter.getNumElements() == 0);

    assert(masterfields.getLength() == 0);
    assert(masterengineouts.getLength() == 0);

    assert(slaves.getLength() == 0);
    assert(auditors.getLength() == 0);
  }
#endif // COIN_DEBUG

  // The container this field is part of.
  SoFieldContainer * container;

  // List of masters we're connected to as a slave. Use maptoconverter
  // dict to find SoFieldConverter engine in the connection (if any).
  SoFieldList masterfields;
  SoEngineOutputList masterengineouts;
  // Fields which are slaves to us. Use maptoconverter dict to find
  // SoFieldConverter engine in the connection (if any).
  SoFieldList slaves;
  // Direct auditors of us.
  SoAuditorList auditors;

  // used to track the last notification (for fanIn handling)
  void * lastnotify;

  // Convenience functions for adding, removing and finding mappings.

  void addConverter(const void * item, SoFieldConverter * converter)
  {
    // "item" can be SoField* or SoEngineOutput*.

    // FIXME: this probably hashes horribly bad, as the item value is
    // a pointer and is therefore address-aligned (lower 32 (?) bits
    // are all 0).  20010911 mortene.
    this->maptoconverter.put(item, converter);
  }

  void removeConverter(const void * item)
  {
    SbBool ok = this->maptoconverter.remove(item);
    assert(ok);
  }

  SoFieldConverter * findConverter(const void * item)
  {
    SoFieldConverter * val;
    if (!this->maptoconverter.get(item, val)) { return NULL; }
    return val;
  }

  SbBool hasFanIn(void) {
    return (this->masterfields.getLength() + this->masterengineouts.getLength()) > 1;
  }
  int findFanInEngine(void) const {
    for (int i = 0; i < this->masterengineouts.getLength(); i++) {
      SoEngineOutput * o = this->masterengineouts[i];
      if (o->isNodeEngineOutput()) {
        if (static_cast<void *>(o->getNodeContainer()) == this->lastnotify) return i;
      }
      else {
        if (static_cast<void *>(o->getContainer()) == this->lastnotify) return i;
      }
    }
    return -1;
  }
  int findFanInField(void) const {
    for (int i = 0; i < this->masterfields.getLength(); i++) {
      if (static_cast<void *>(this->masterfields[i]->getContainer()) == this->lastnotify) return i;
    }
    return -1;
  }


  // Provides us with a hack to get at a master field's type in code
  // called from its constructor (SoField::getTypeId() is virtual and
  // can't be used).
  //
  // (Used in the master::~SoField() -> slave::disconnect(master)
  // chain.)
  SoType fieldtype;
  void add_vrml2_routes(SoOutput * out, const SoField * f);

private:
  // Dictionary of void* -> SoFieldConverter* mappings.
  SbHash<SoFieldConverter *, const void *> maptoconverter;

};

// helper function. Used to check if field is in a vrml2 node
static SbBool
is_vrml2_field(const SoField * f)
{
  assert(f);
  SoFieldContainer * fc = f->getContainer();
  // test fc to support fields with no container
  if (fc && fc->isOfType(SoNode::getClassTypeId())) {
    if (fc->isOfType(SoProtoInstance::getClassTypeId())) return TRUE;
    if (coin_assert_cast<SoNode *>(fc)->getNodeType() & SoNode::VRML2) return TRUE;
  }

  return FALSE;
}

//
// add all connections to this field as routes in SoOutput.  SoOutput
// will decide when to write the ROUTEs.
//
void
SoConnectStorage::add_vrml2_routes(SoOutput * out, const SoField * f)
{
  SoFieldContainer * tofc = f->getContainer();
  assert(tofc);
  SbName toname, fromname;
  (void) tofc->getFieldName(f, toname);

  int i;
  for (i = 0; i < this->masterfields.getLength(); i++) {
    SoField * master = this->masterfields[i];
    SoFieldContainer * fc = master->getContainer();
    assert(fc);
    (void) fc->getFieldName(master, fromname);

    if (out->getStage() == SoOutput::COUNT_REFS) {
      fc->addWriteReference(out, TRUE);
      tofc->addWriteReference(out, TRUE);
    }
    else {
      out->addRoute(fc, fromname, tofc, toname);
    }
  }
  for (i = 0; i < this->masterengineouts.getLength(); i++) {
    SoEngineOutput * engineout = this->masterengineouts[i];
    SoFieldContainer * fc = engineout->getFieldContainer();
    if (engineout->isNodeEngineOutput()) {
      SoNodeEngine * engine = engineout->getNodeContainer();
      assert(engine);
      (void) engine->getOutputName(engineout, fromname);
    }
    else {
      SoEngine * engine = engineout->getContainer();
      assert(engine);
      (void) engine->getOutputName(engineout, fromname);
    }
    if (out->getStage() == SoOutput::COUNT_REFS) {
      fc->addWriteReference(out, TRUE);
      tofc->addWriteReference(out, TRUE);
    }
    else {
      out->addRoute(fc, fromname, tofc, toname);
    }
  }
}

// Collects some private code for SoField.
//
// Note that there is no private implementation data pointer (aka
// "pimpl" or Cheshire Cat) for the SoField instances, as they should
// be as slim as possible. Therefore, this class only contains static
// functions.
class SoFieldP {
public:
  // Convenience method to extract a string that identifies the field
  // with as much relevant info as possible. Used from other debug
  // output code.
  static SbString getDebugIdString(const SoField * f)
  {
    SoFieldContainer * fcontainer = f->getContainer();
    SbName fname("<no-container>");
    if (fcontainer) {
      SbBool ok = fcontainer->getFieldName(f, fname);
      if (!ok) { fname = "<not-yet-added>"; }
    }
    SbString s;
    s.sprintf("field==%p/%s/'%s'",
              f,
              f->getTypeId().getName().getString(),
              fname.getString());
    return s;
  }

  static SbHash<char **, char *> * getReallocHash(void);
  static void * hashRealloc(void * bufptr, size_t size);

  static SbHash<char **, char *> * ptrhash;
};

SbHash<char **, char *> * SoFieldP::ptrhash = NULL;

extern "C" {
// atexit callbacks
static void SoField_cleanupClass(void);
static void hashExitCleanup(void);
static void field_mutex_cleanup(void);
}

SbHash<char **, char *> *
SoFieldP::getReallocHash(void)
{
  // FIXME: protect with mutex?
  if (SoFieldP::ptrhash == NULL) {
    SoFieldP::ptrhash = new SbHash<char **, char *>;
    coin_atexit(hashExitCleanup, CC_ATEXIT_NORMAL);
  }
  return SoFieldP::ptrhash;
}

void
hashExitCleanup(void)
{
  assert(SoFieldP::ptrhash->getNumElements() == 0);
  delete SoFieldP::ptrhash;
  SoFieldP::ptrhash = NULL;
}

void *
SoFieldP::hashRealloc(void * bufptr, size_t size)
{
  CC_MUTEX_LOCK(sofield_mutex);

  char ** bufptrptr = NULL;
  int ok = SoFieldP::ptrhash->get(static_cast<char *>(bufptr), bufptrptr);
  assert(ok);

  // If *bufptrptr contains a NULL pointer, this is the first
  // invocation and the initial memory buffer was on the stack.
  char * newbuf;
  if (*bufptrptr == NULL) {
    // if initial buffer was on the stack, we need to manually copy
    // the data into the new buffer.
    newbuf = static_cast<char *>(malloc(size));
    memcpy(newbuf, bufptr, SOFIELD_GET_STACKBUFFER_SIZE);
  }
  else {
    newbuf = static_cast<char *>(realloc(bufptr, size));
  }
  if (newbuf != bufptr) {
    ok = SoFieldP::ptrhash->remove(static_cast<char *>(bufptr));
    assert(ok);
    *bufptrptr = newbuf;
    SoFieldP::ptrhash->put(newbuf, bufptrptr);
  }

  CC_MUTEX_UNLOCK(sofield_mutex);

  return newbuf;
}

// *************************************************************************

// Documentation for abstract methods.

// FIXME: grab better version of getTypeId() doc from SoBase, SoAction
// and / or SoDetail. 20010913 mortene.
/*!
  \fn SoType SoField::getTypeId(void) const

  Returns the type identification instance which uniquely identifies
  the Coin field class the object belongs to.

  \sa getClassTypeId(), SoType
*/

/*!
  \fn SbBool SoField::isSame(const SoField & f) const
  Check for equal type and value(s).
*/

/*!
  \fn void SoField::copyFrom(const SoField & f)

  Copy value(s) from \a f into this field. \a f must be of the same
  type as this field.
*/

/*!
  \fn SbBool SoField::readValue(SoInput * in)
  Read field value(s).
*/

/*!
  \fn void SoField::writeValue(SoOutput * out) const
  Write field value(s).
*/


// *************************************************************************

SoType SoField::classTypeId STATIC_SOTYPE_INIT;

// *************************************************************************

// used to detect when a field that is already destructed is used
#define FLAG_ALIVE_PATTERN 0xbeef0000

// private methods. Inlined inside this file only.

// clear bits in statusbits
inline void
SoField::clearStatusBits(const unsigned int bits)
{
  this->statusbits &= ~bits;
}

// sets bits in statusbits
inline void
SoField::setStatusBits(const unsigned int bits)
{
  this->statusbits |= bits;
}

// return TRUE if any of bits is set
inline SbBool
SoField::getStatus(const unsigned int bits) const
{
  return (this->statusbits & bits) != 0;
}

// convenience method for clearing or setting based on boolean value
// returns TRUE if any bitflag changed value
inline SbBool
SoField::changeStatusBits(const unsigned int bits, const SbBool onoff)
{
  unsigned int oldval = this->statusbits;
  unsigned int newval = oldval;
  if (onoff) newval |= bits;
  else newval &= ~bits;
  if (oldval != newval) {
    this->statusbits = newval;
    return TRUE;
  }
  return FALSE;
}

// returns TRUE if this field has ext storage
inline SbBool
SoField::hasExtendedStorage(void) const
{
  return this->getStatus(FLAG_EXTSTORAGE);
}


/*!
  This is the base constructor for field classes. It takes care of
  doing the common parts of data initialization in fields.
*/
SoField::SoField(void)
  : container(NULL)
{
  this->statusbits = 0;
  this->setStatusBits(FLAG_DONOTIFY |
                      FLAG_ISDEFAULT |
                      FLAG_ENABLECONNECTS|
                      FLAG_ALIVE_PATTERN);
}

/*!
  Destructor. Disconnects ourself from any connected field or engine
  before we disconnect all auditors on the field.
*/
SoField::~SoField()
{
  // set status bit to avoid evaluating this field while
  // disconnecting connections.
  this->setStatusBits(FLAG_ISDESTRUCTING);

#if COIN_DEBUG && 0 // debug
  SoDebugError::postInfo("SoField::~SoField", "destructing %p", this);
#endif // debug

  // Disconnect ourself from all connections where this field is the
  // slave.
  this->disconnect();

  if (this->hasExtendedStorage()) {

    // Disconnect slave fields using us as a master.
    while (this->storage->slaves.getLength()) {
      this->storage->slaves[0]->disconnect(this);
    }

    // Disconnect other auditors.
    while (this->storage->auditors.getLength()) {
      SoNotRec::Type type = this->storage->auditors.getType(0);
      void * obj = this->storage->auditors.getObject(0);

      switch (type) {
      case SoNotRec::ENGINE:
        static_cast<SoEngineOutput *>(obj)->removeConnection(this);
        break;

      case SoNotRec::CONTAINER:
        assert(FALSE && "Container should not be in auditorlist");
        break;

      case SoNotRec::SENSOR:
        static_cast<SoDataSensor *>(obj)->dyingReference();
        break;

      case SoNotRec::FIELD:
        assert(FALSE); // should not happen, as slave fields are removed first.
        break;

      default:
        assert(FALSE); // no other allowed types.
        break;
      }
    }

    delete this->storage;
  }
#if COIN_DEBUG && 0 // debug
  SoDebugError::postInfo("SoField::~SoField", "%p done", this);
#endif // debug

  this->clearStatusBits(FLAG_ALIVE_PATTERN);
}

// atexit
void
field_mutex_cleanup(void)
{
  CC_MUTEX_DESTRUCT(sofield_mutex);
}

/*!
  Internal method called upon initialization of the library (from
  SoDB::init()) to set up the type system.
*/
void
SoField::initClass(void)
{
  // Make sure we only initialize once.
  assert(SoField::classTypeId == SoType::badType());

  CC_MUTEX_CONSTRUCT(sofield_mutex);
  coin_atexit(field_mutex_cleanup, CC_ATEXIT_NORMAL);

  SoField::classTypeId = SoType::createType(SoType::badType(), "Field");
  SoField::initClasses();
  coin_atexit(SoField_cleanupClass, CC_ATEXIT_NORMAL);
}

void
SoField_cleanupClass(void)
{
  SoField::cleanupClass();
}

void
SoField::cleanupClass(void)
{
  SoField::classTypeId STATIC_SOTYPE_INIT;
}

/*!
  Sets the flag which indicates whether or not the field should be
  ignored during certain operations.

  The effect of this flag depends on what type of field it is used on,
  and the type of the node which includes the field.

  This flag is represented in Inventor files by a ~ behind the field
  name.  The flag is in other words persistent.

  \sa isIgnored()
*/
void
SoField::setIgnored(SbBool ignore)
{
  if (this->changeStatusBits(FLAG_IGNORE, ignore)) {
    this->valueChanged(FALSE);
  }
}

/*!
  Returns the ignore flag.

  \sa setIgnored()
*/
SbBool
SoField::isIgnored(void) const
{
  return this->getStatus(FLAG_IGNORE);
}

/*!
  Set whether or not this field should be marked as containing a
  default value.

  \sa isDefault()
*/
void
SoField::setDefault(SbBool def)
{
#if COIN_DEBUG && 0 // debug
  SbString finfo = SoFieldP::getDebugIdString(this);
  SoDebugError::postInfo("SoField::setDefault", "%s, setDefault(%s)",
                         finfo.getString(), def ? "TRUE" : "FALSE");
#endif // debug

  (void) this->changeStatusBits(FLAG_ISDEFAULT, def);
}

/*!
  Check if the field contains its default value. Fields which has
  their default value intact will normally not be included in the
  output when writing scene graphs out to a file, for instance.

  \sa setDefault()
*/
SbBool
SoField::isDefault(void) const
{
  return this->getStatus(FLAG_ISDEFAULT);
}

/*!
  Returns a unique type identifier for this field class.

  \sa getTypeId(), SoType
*/
SoType
SoField::getClassTypeId(void)
{
  return SoField::classTypeId;
}

/*!
  Check if this instance is of a derived type or is the same type as
  the one given with the \a type parameter.
*/
SbBool
SoField::isOfType(const SoType type) const
{
  return this->getTypeId().isDerivedFrom(type);
}

/*!
  This sets a \a flag value which indicates whether or not the set up
  connection should be considered active. For as long as the "enable
  connection" flag is \c FALSE, no value propagation will be done from
  any connected source field, engine or interpolator into this field.

  If the connection is first disabled and then enabled again, the
  field will automatically be synchronized with any master field,
  engine or interpolator.

  \sa isConnectionEnabled()
*/
void
SoField::enableConnection(SbBool flag)
{
  SbBool oldval = this->getStatus(FLAG_ENABLECONNECTS);
  (void) this->changeStatusBits(FLAG_ENABLECONNECTS, flag);
  if (!oldval && flag) this->setDirty(TRUE);
}

/*!
  Return the current status of the connection enabled flag.

  \sa enableConnection()
*/
SbBool
SoField::isConnectionEnabled(void) const
{
  return this->getStatus(FLAG_ENABLECONNECTS);
}

/*!
  Connects this field as a slave to \a master. This means that the
  value of this field will be automatically updated when \a master is
  changed (as long as the connection also is enabled).

  If this field had any connections to master fields beforehand, these
  are all broken up if \a append is \c FALSE.

  Call with \a notnotify if you want to avoid the initial notification
  of connected auditors (a.k.a. \e slaves).

  Function will return \c TRUE unless:

  \li If the field connected \e from has a different type from the
      field connected \e to, a field converter is inserted. For some
      combinations of fields no such conversion is possible, and we'll
      return \c FALSE.

  \li If this field is already connected to the \a master, we will
      return \c FALSE.

  \sa enableConnection(), isConnectionEnabled(), isConnectedFromField()
  \sa getConnectedField(), appendConnection(SoField *)
*/
SbBool
SoField::connectFrom(SoField * master, SbBool notnotify, SbBool append)
{
  // detect and ref() global fields. This is done to automatically
  // detect when the last reference to a global field is deleted
  if (master->getContainer() && master->getContainer()->isOfType(SoGlobalField::getClassTypeId())) {
    master->getContainer()->ref();
  }
  // Initialize.  /////////////////////////////////////////////////

  this->extendStorageIfNecessary();
  master->extendStorageIfNecessary();

  SoType mastertype = master->getTypeId();
  SoType thistype = this->getTypeId();
  SbBool containerisconverter = this->getContainer() &&
    this->getContainer()->getTypeId().isDerivedFrom(SoFieldConverter::getClassTypeId());


  // Set up all links.  ///////////////////////////////////////////

  if (mastertype == thistype) { // Can do direct field-to-field link.
    if (!append) this->disconnect();
    else if (this->storage->masterfields.find(master) >= 0) {
      // detect and avoid multiple connections between the same fields
      // (a common bug in VRML files created by 3ds max).
#if COIN_DEBUG
      SoFieldContainer * fc = master->getContainer();
      SbName fcname = fc ? fc->getName() : SbName::empty();
      if (fcname != SbName::empty()) {
        SbName fieldname;
        (void) fc->getFieldName(master, fieldname);
        SoDebugError::postWarning("SoField::connectFrom",
                                  "connection from %p (%s.%s) already made",
                                  master,
                                  fcname.getString(),
                                  fieldname.getString());

      }
      else {
        SoDebugError::postWarning("SoField::connectFrom",
                                  "connection from %p already made", master);
      }
#endif // COIN_DEBUG
      return FALSE;
    }
    // Set up the auditor link from the master to the slave field.
    // (Note that the ``this'' slave field can also be an input field
    // of an SoFieldConverter instance.)
    master->addAuditor(this, SoNotRec::FIELD);
  }
  else { // Needs an SoFieldConverter between the fields.
    SoFieldConverter * conv = this->createConverter(mastertype);
    if (!conv) {
      // Just return FALSE and don't bother to warn, as that is done
      // by the createConverter() method.
      return FALSE;
    }

    if (!append) this->disconnect();

    // Link up the input SoField of the SoFieldConverter to the master
    // field by recursively calling connectFrom().
    SoField * converterinput = conv->getInput(mastertype);
    // the converter engine should always be notified upon connection
    // as it will never have a default value read in from a file.
    converterinput->connectFrom(master, FALSE);

    // Connect from the SoFieldConverter output to the slave field.
    SoEngineOutput * converteroutput =
      conv->getOutput(SoType::badType()); // dummy type
    converteroutput->addConnection(this);

    // Remember the connection from the slave field to the
    // SoFieldConverter by setting up a dict entry.
    this->storage->addConverter(master, conv);
  }

  // Common bookkeeping.
  this->storage->masterfields.append(master); // slave -> master link
  if (!containerisconverter)
    master->storage->slaves.append(this); // master -> slave link


  // Notification.  ///////////////////////////////////////////////

  if ((notnotify == FALSE) && this->isConnectionEnabled()) {
    this->setDirty(TRUE);
    this->setDefault(FALSE);
    this->startNotify();
  }

  return TRUE;
}

/*!
  Connects this field as a slave to \a master. This means that the value
  of this field will be automatically updated when \a master is changed (as
  long as the connection also is enabled).

  If this field had any master-relationships beforehand, these are all
  broken up if \a append is \c FALSE.

  Call with \a notnotify if you want to avoid the initial notification
  of connected auditors (a.k.a. \e slaves).

  Function will return \c TRUE unless:

  \li If the field output connected \e from is of a different type
      from the engine output field-type connected \e to, a field
      converter is inserted. For some combinations of fields no such
      conversion is possible, and we'll return \c FALSE.

  \li If this field is already connected to the \a master, we will
      return \c FALSE.

  \sa enableConnection(), isConnectionEnabled(), isConnectedFromField()
  \sa getConnectedField(), appendConnection(SoEngineOutput *)
*/
SbBool
SoField::connectFrom(SoEngineOutput * master, SbBool notnotify, SbBool append)
{
  // Initialize.  /////////////////////////////////////////////////

  this->extendStorageIfNecessary();

  SoType mastertype = master->getConnectionType();
  SoType thistype = this->getTypeId();

  // If we connectFrom() on the same engine as the field is already
  // connected to, we want to avoid the master container engine being
  // unref()'ed down to ref-count 0 upon the disconnect().
  SoFieldContainer * masterengine = master->getFieldContainer();

  if (masterengine) masterengine->ref();


  // Set up all links.  ///////////////////////////////////////////

  if (mastertype == thistype) { // Can do direct field-to-engineout link.
    if (!append) this->disconnect();
    else {
      // check if we're already connected
      if (this->storage->masterengineouts.find(master) >= 0) {
        // detect and avoid multiple connections between the same
        // field and engine output (a common bug in VRML files
        // created by 3ds max).
#if COIN_DEBUG
        SoDebugError::postWarning("SoField::connectFrom",
                                  "connection from %p already made", master);
#endif // COIN_DEBUG
        // Match the ref() invocation.
        if (masterengine) masterengine->unref();
        return FALSE;
      }
    }
    // Set up the auditor link from the master engineout to the slave
    // field.  (Note that the ``this'' slave field can also be an
    // input field of an SoFieldConverter instance.)

    // This is enough, the container SoEngine will automatically pick
    // up on it.
    master->addConnection(this);
  }
  else { // Needs an SoFieldConverter between this field and the SoEngineOutput
    SoFieldConverter * conv = this->createConverter(mastertype);
    if (!conv) { // Handle this exception.
      // Clean up the ref().
      if (masterengine) masterengine->unref();
      // Sorry, can't connect. Don't bother to spit out a warning, as
      // that is done in createConverter().
      return FALSE;
    }

    if (!append) this->disconnect();

    // Link up the input SoField of the SoFieldConverter to the master
    // SoEngineOutput by recursively calling connectFrom().
    SoField * converterinput = conv->getInput(mastertype);
    // the converter engine should always be notified upon connection
    // as it will never have a default value read in from a file
    converterinput->connectFrom(master, FALSE);

    // Connect from the SoFieldConverter output to the slave field.
    SoEngineOutput * converteroutput =
      conv->getOutput(SoType::badType()); // dummy type
    converteroutput->addConnection(this);

    // Remember the connection from the slave field to the
    // SoFieldConverter by setting up a dict entry.
    this->storage->addConverter(master, conv);
  }

  // Match the ref() invocation.
  if (masterengine) masterengine->unref();

  // Common bookkeeping.
  this->storage->masterengineouts.append(master); // slave -> master link

  // Notification.  ///////////////////////////////////////////////

  if ((notnotify == FALSE) && this->isConnectionEnabled()) {
    this->setDirty(TRUE);
    this->setDefault(FALSE);
    this->startNotify();
  }

  return TRUE;
}


/*!
  Disconnect this field as a slave from \a master.
*/
void
SoField::disconnect(SoField * master)
{
#if COIN_DEBUG && 0 // debug
  SoDebugError::postInfo("SoField::disconnect",
                         "removing slave field %p from master field %p",
                         this, master);
#endif // debug

  const int idx = this->storage->masterfields.find(master);
  if (idx == -1) {
    SoDebugError::post("SoField::disconnect",
                       "can't disconnect from a field which we're not connected to!");
    return;
  }

  this->evaluate();

  SbBool containerisconverter = this->getContainer() &&
    this->getContainer()->getTypeId().isDerivedFrom(SoFieldConverter::getClassTypeId());


  // Decouple links. ///////////////////////////////////////////////////

  // Remove bookkeeping material.
  if (!containerisconverter) master->storage->slaves.removeItem(this);

  this->storage->masterfields.remove(idx);

  SoFieldConverter * converter = this->storage->findConverter(master);
  if (converter) { // There's a converter engine between the fields.

    SoField * converterinput =
      converter->getInput(SoType::badType()); // dummy type
    converterinput->disconnect(master);

    SoEngineOutput * converteroutput =
      converter->getOutput(SoType::badType()); // dummy type
    converteroutput->removeConnection(this);

    this->storage->removeConverter(master);
    converter->unref();
  }
  else { // No converter, just a direct link.
    master->removeAuditor(this, SoNotRec::FIELD);
  }

  // detect and unref() global fields. This is done to detect when the
  // last reference to a global fields is deleted.
  if (master->getContainer() && master->getContainer()->isOfType(SoGlobalField::getClassTypeId())) {
    master->getContainer()->unref();
  }
}

/*!
  Disconnect this field as a slave from \a master.
*/
void
SoField::disconnect(SoEngineOutput * master)
{
  // First check to see we're the input field of an
  // SoFieldConverter. If so, recursively call disconnect() with the
  // field on "the other side" of the converter.

  SoType fieldconvtype = SoFieldConverter::getClassTypeId();
  SbBool containerisconverter =
    this->getContainer() &&
    this->getContainer()->getTypeId().isDerivedFrom(fieldconvtype);
  if (containerisconverter) {
    SoFieldConverter * converter =
      coin_assert_cast<SoFieldConverter *>(this->getContainer());
    SoEngineOutput * converterout =
      converter->getOutput(SoType::badType()); // dummy type
    SoFieldList fl;
    converterout->getForwardConnections(fl);
    fl[0]->disconnect(master);
    return;
  }


#if COIN_DEBUG && 0 // debug
  SoDebugError::postInfo("SoField::disconnect",
                         "removing slave field %p (%s.%s) from master "
                         "engineout %p",
                         this,
                         this->storage->container->getTypeId().getName().getString(),
                         this->storage->fieldtype.getName().getString(),
                         master);
#endif // debug


  // Check the enabled flag to avoid evaluating from engines which are
  // being destructed. This is a bit of a hack, but I don't think it
  // matters.   -- mortene.
  if (master->isEnabled()) this->evaluate();

  // Decouple links. ///////////////////////////////////////////////////

  // Remove bookkeeping material.
  this->storage->masterengineouts.removeItem(master);

  SoFieldConverter * converter = this->storage->findConverter(master);
  if (converter) { // There's a converter engine between the fields.
    SoField * converterinput =
      converter->getInput(SoType::badType()); // dummy type
    converterinput->storage->masterengineouts.removeItem(master);
    master->removeConnection(converterinput);

    SoEngineOutput * converteroutput =
      converter->getOutput(SoType::badType()); // dummy type
    converteroutput->removeConnection(this);

    this->storage->removeConverter(master);
    converter->unref();
  }
  else { // No converter, just a direct link.
    master->removeConnection(this);
  }
}

/*!
  Returns number of fields this field is a slave of.

  \sa getConnections()
*/
int
SoField::getNumConnections(void) const
{
  return this->hasExtendedStorage() ?
    this->storage->masterfields.getLength() : 0;
}

/*!
  Returns number of masters this field is connected to, and places
  pointers to all of them into \a masterlist.

  Note that we replace the contents of \a masterlist, i.e. we're \e
  not appending new data.

  \sa getNumConnections()
*/
int
SoField::getConnections(SoFieldList & masterlist) const
{
  if (!this->hasExtendedStorage()) return 0;

  masterlist = this->storage->masterfields;
  return masterlist.getLength();
}

/*!
  Disconnect all connections from this field as a slave to master
  fields or engine outputs.
*/
void
SoField::disconnect(void)
{
  // Disconnect us from all master fields.
  while (this->isConnectedFromField())
    this->disconnect(this->storage->masterfields[0]);

  // Disconnect us from all master engine outputs.
  while (this->isConnectedFromEngine())
    this->disconnect(this->storage->masterengineouts[0]);

  assert(this->isConnected() == FALSE);
}

/*!
  Returns \c TRUE if we're connected from another field, engine or
  interpolator.

  \sa isConnectedFromField(), isConnectedFromEngine()
  \sa connectFrom()
*/
SbBool
SoField::isConnected(void) const
{
  return (this->isConnectedFromField() ||
          this->isConnectedFromEngine());
}

/*!
  Returns \c TRUE if we're a slave of at least one field.

  \sa isConnected(), isConnectedFromEngine()
  \sa connectFrom(SoField *)
*/
SbBool
SoField::isConnectedFromField(void) const
{
  return (this->hasExtendedStorage() &&
          this->storage->masterfields.getLength() > 0);
}

/*!
  Returns \c TRUE if we're connected from an engine.

  \sa isConnected(), isConnectedFromField()
  \sa connectFrom(SoEngineOutput *)
*/
SbBool
SoField::isConnectedFromEngine(void) const
{
  return (this->hasExtendedStorage() &&
          this->storage->masterengineouts.getLength() > 0);
}

// Simplify by collecting common code for SoField::getConnected*() methods.
#define SOFIELD_GETCONNECTED(_masterlist_) \
  if (!this->hasExtendedStorage()) return FALSE; \
  int nrmasters = this->storage->_masterlist_.getLength(); \
  if (nrmasters < 1) return FALSE; \
  master = this->storage->_masterlist_[nrmasters - 1]; \
  return TRUE

/*!
  Returns \c TRUE if we are connected as a slave to at least one other
  field.  \a master will be set to the source field in the last field
  connection made.

  \sa isConnectedFromField(), connectFrom(SoField *),
  \sa appendConnection(SoField *)
*/
SbBool
SoField::getConnectedField(SoField *& master) const
{
  SOFIELD_GETCONNECTED(masterfields);
}

/*!
  Returns \c TRUE if we are connected as a slave to at least one
  engine. \a master will be set to the source of the last engine
  connection made.

  \sa isConnectedFromEngine(), connectFrom(SoEngineOutput *)
  \sa appendConnection(SoEngineOutput *)
*/
SbBool
SoField::getConnectedEngine(SoEngineOutput *& master) const
{
  SOFIELD_GETCONNECTED(masterengineouts);
}

#undef SOFIELD_GETCONNECTED

/*!
  Appends all the fields which are auditing this field in \a
  slavelist, and returns the number of fields which are our slaves.
*/
int
SoField::getForwardConnections(SoFieldList & slavelist) const
{
  if (!this->hasExtendedStorage()) return 0;

  int nr = 0;

  for (int i=0; i < this->storage->slaves.getLength(); i++) {
    slavelist.append(this->storage->slaves[i]);
    nr++;
  }

  return nr;
}

/*!
  Let the field know to which container it belongs.

  \sa getContainer(), SoFieldContainer
*/
void
SoField::setContainer(SoFieldContainer * cont)
{
  if (!this->hasExtendedStorage()) this->container = cont;
  else this->storage->container = cont;

  // The field should have been set to its default value before it is
  // added to the container.
  //
  // This might seem strange, but it looks like it is necessary to do
  // it this way to be compatible with Open Inventor.
  this->setDefault(TRUE);
}

/*!
  Returns the SoFieldContainer object "owning" this field.

  \sa SoFieldContainer, setContainer()
*/
SoFieldContainer *
SoField::getContainer(void) const
{
  if (!this->hasExtendedStorage()) return this->container;
  else return this->storage->container;
}

/*!
  Set the field's value through the given \a valuestring. The format
  of the string must adhere to the ASCII format used in Coin data
  format files.

  Only the value should be specified - \e not the name of the field.

  \c FALSE is returned if the field value is invalid for the field
  type and can't be parsed in any sensible way.

  \sa get()
*/
SbBool
SoField::set(const char * valuestring)
{
  // Note that it is not necessary to set a header identification line
  // for this to work.
  SoInput in;
  in.setBuffer(const_cast<char *>(valuestring), strlen(valuestring));
  if (!this->readValue(&in)) return FALSE;

  this->valueChanged();
  return TRUE;
}

/*!
  Returns the field's value as an ASCII string in the export data
  format for Inventor files.

  \sa set()
*/
void
SoField::get(SbString & valuestring)
{
  // FIXME: this function should be const! 20050607 mortene.

  // NOTE: this code has an almost verbatim copy in SoMField::get1(),
  // so remember to update both places if any fixes are done.

  // Initial buffer setup.
  SoOutput out;
  char initbuffer[SOFIELD_GET_STACKBUFFER_SIZE];
  char * bufferptr = NULL; // indicates that initial buffer is on the stack

  CC_MUTEX_LOCK(sofield_mutex);
  int ok = SoFieldP::getReallocHash()->put(initbuffer, &bufferptr);
  assert(ok);
  CC_MUTEX_UNLOCK(sofield_mutex);

  out.setBuffer(initbuffer, sizeof(initbuffer), SoFieldP::hashRealloc);

  // Record offset to skip header.
  out.write("");
  size_t offset;
  void * buffer;
  out.getBuffer(buffer, offset);

  // Write field..
  out.setStage(SoOutput::COUNT_REFS);
  this->countWriteRefs(&out);
  out.setStage(SoOutput::WRITE);
  this->writeValue(&out);

  // ..then read it back into the SbString.
  size_t size;
  out.getBuffer(buffer, size);
  valuestring = static_cast<char *>(buffer) + offset;

  // dealloc tmp memory buffer
  if (bufferptr) { free(bufferptr); }

  CC_MUTEX_LOCK(sofield_mutex);
  ok = SoFieldP::getReallocHash()->remove(bufferptr ? bufferptr : initbuffer);
  assert(ok);
  CC_MUTEX_UNLOCK(sofield_mutex);
}

/*!
  Notify the field as well as the field's owner / container that it
  has been changed.

  Touching a field which is part of any component (engine or node) in
  a scene graph will lead to a forced redraw. This is useful if you
  have been doing several updates to the field wrapped in a pair of
  enableNotify() calls to notify the field's auditors that its value
  has changed.

  \sa setValue(), enableNotify()
*/
void
SoField::touch(void)
{
  if (this->container) this->startNotify();
}

/*!
  Trigger a notification sequence.

  At the end of a notification sequence, all "immediate" sensors
  (i.e. sensors set up with a zero priority) are triggered.
*/
void
SoField::startNotify(void)
{
  SoNotList l;
#if COIN_DEBUG && 0 // debug
  SoDebugError::postInfo("SoField::startNotify", "field %p (%s), list %p",
                         this, this->getTypeId().getName().getString(), &l);
#endif // debug

  SoDB::startNotify();
  this->notify(&l);
  SoDB::endNotify();

#if COIN_DEBUG && 0 // debug
  SoDebugError::postInfo("SoField::startNotify", "DONE\n\n");
#endif // debug
}

/*!
  Notify auditors that this field has changed.
*/
void
SoField::notify(SoNotList * nlist)
{
  assert((this->statusbits & FLAG_ALIVE_PATTERN) == FLAG_ALIVE_PATTERN);
#if COIN_DEBUG
  if (this->getContainer()) {
    this->getContainer()->assertAlive();
  }
#endif // COIN_DEBUG

  // check NotRec type to find if the notification was from a
  // connection. If someone changes the field directly we should
  // just continue.

  SoNotRec * rec = nlist->getLastRec();
  if (rec) {
    SoNotRec::Type t = nlist->getLastRec()->getType();
    if (t == SoNotRec::ENGINE || t == SoNotRec::FIELD) {
      if (this->hasExtendedStorage()) {
        this->storage->lastnotify = static_cast<void *>(rec->getBase());
      }
      // don't process the notification if we're notified from a
      // connection, and connection is disabled (through
      // enableConnection())
      if (!this->isConnectionEnabled()) return;
    }
  }

  // In Inventor it is legal to have circular field connections. This
  // test stops the notification from entering into an infinite
  // recursion because of such connections. The flag is set/cleared
  // before/after progagating the notification.
  if (this->getStatus(FLAG_ISNOTIFIED)) return;

  // needed because of the So[SF|MF]Node fields. When a node inside
  // such a field is changed we must mark the field as not default so
  // that SoWriteAction will export it. We can safely call
  // setDefault(FALSE) for other field types as well, since the only
  // other reason for entering here is if the field is connected from
  // an engine output or from another field.
  this->setDefault(FALSE);

#if COIN_DEBUG && 0 // debug
  if (this != SoDB::getGlobalField("realTime")) {
    SoDebugError::postInfo("SoField::notify", "%p (%s (%s '%s')) -- start",
                           this,
                           this->getTypeId().getName().getString(),
                           this->getContainer() ? this->getContainer()->getTypeId().getName().getString() : "*none*",
                           this->getContainer() ? this->getContainer()->getName().getString() : "*none*");
  }
#endif // debug

  // If we're not the originator of the notification process, we need
  // to be marked dirty, as it means something we're connected to as a
  // slave has changed and our value needs to be updated.
  //
  // Note: don't try to "optimize" code here by moving the setDirty()
  // call down into the isNotifyEnabled() check, as setDirty()
  // _should_ happen if we're not the originator -- no matter what the
  // status of the notification enable flag is.
  if (nlist->getFirstRec()) this->setDirty(TRUE);

  if (this->isNotifyEnabled()) {
    SoFieldContainer * container = this->getContainer();
    this->setStatusBits(FLAG_ISNOTIFIED);
    SoNotRec rec(container);
    nlist->append(&rec, this);
    nlist->setLastType(SoNotRec::CONTAINER); // FIXME: Not sure about this. 20000304 mortene.

#if COIN_DEBUG && 0 // debug
    SoDebugError::postInfo("SoField::notify",
                           "field %p, list %p", this, nlist);
#endif // debug

    if (this->hasExtendedStorage() && this->storage->auditors.getLength()) {
      // need to copy list first if we're going to notify the auditors
      SoNotList listcopy(*nlist);
      if (container) container->notify(nlist);
      this->notifyAuditors(&listcopy);
    }
    else {
      if (container) container->notify(nlist);
    }
    this->clearStatusBits(FLAG_ISNOTIFIED);
  }

#if COIN_DEBUG && 0 // debug
  if (this != SoDB::getGlobalField("realTime")) {
    SoDebugError::postInfo("SoField::notify", "%p (%s (%s '%s')) -- done",
                           this,
                           this->getTypeId().getName().getString(),
                           this->getContainer() ? this->getContainer()->getTypeId().getName().getString() : "*none*",
                           this->getContainer() ? this->getContainer()->getName().getString() : "*none*");
  }
#endif // debug
}

/*!
  This method sets whether notification will be propagated on changing
  the value of the field.  The old value of the setting is returned.

  \sa isNotifyEnabled()
*/
SbBool
SoField::enableNotify(SbBool on)
{
  const SbBool old = this->getStatus(FLAG_DONOTIFY);
  (void) this->changeStatusBits(FLAG_DONOTIFY, on);
  return old;
}

/*!
  This method returns whether notification of changes to the field
  value are propagated to the auditors.

  \sa enableNotify()
*/
SbBool
SoField::isNotifyEnabled(void) const
{
  return this->getStatus(FLAG_DONOTIFY);
}

// Makes an extended storage block on first connection.
void
SoField::extendStorageIfNecessary(void)
{
  if (!this->hasExtendedStorage()) {
    this->storage = new SoConnectStorage(this->container, this->getTypeId());
    this->setStatusBits(FLAG_EXTSTORAGE);
  }
}

/*!
  Add an auditor to the list. All auditors will be notified whenever
  this field changes its value(s).
*/
void
SoField::addAuditor(void * f, SoNotRec::Type type)
{
  this->extendStorageIfNecessary();
  this->storage->auditors.append(f, type);
  this->connectionStatusChanged(+1);
}

/*!
  Remove an auditor from the list.
*/
void
SoField::removeAuditor(void * f, SoNotRec::Type type)
{
#if COIN_DEBUG && 0 // debug
  SoDebugError::postInfo("SoField::removeAuditor",
                         "%p removing %p", this, f);
#endif // debug

  assert(this->hasExtendedStorage());
  this->storage->auditors.remove(f, type);
  this->connectionStatusChanged(-1);
}

/*!
  Checks for equality. Returns \c 0 if the fields are of different
  type or the field's value(s) are not equal.
*/
int
SoField::operator ==(const SoField & f) const
{
  return this->isSame(f);
}

/*!
  Returns \c TRUE if the fields are of different type or has different
  value.
*/
int
SoField::operator !=(const SoField & f) const
{
  return !this->isSame(f);
}

/*!
  Returns \c TRUE if it is necessary to write the field when dumping a
  scene graph. This needs to be done if the field is not default (it
  has been changed from its default value), if it's ignored, or if
  it's connected from another field or engine.
*/
SbBool
SoField::shouldWrite(void) const
{
#if COIN_DEBUG && 0 // debug
  SbString finfo = SoFieldP::getDebugIdString(this);
  SoDebugError::postInfo("SoField::shouldWrite",
                         "%s: isDefault==%d, isIgnored==%d, isConnected==%d",
                         finfo.getString(), this->isDefault(),
                         this->isIgnored(), this->isConnected());
#endif // debug

  if (!this->isDefault()) return TRUE;
  if (this->isIgnored()) return TRUE;

  if (this->isConnected()) {
#if 0 // disabled (was only needed for bidirectional connections in PROTOs)
    // I suspect this code was here only to make the bidirectional
    // connection hack in SoProto work. Connected PROTO instance
    // fields should be written even if they have the default value
    // (just like any other field). pederb, 2005-12-20
    SoFieldContainer * thecontainer = this->getContainer();
    if ( thecontainer != NULL &&
         thecontainer->isOfType(SoProtoInstance::getClassTypeId()) ) {
      // PROTO instance fields are usually connected, but we don't want to
      // write out PROTO instance fields that contain default values - they
      // will be hooked up and get the default value from the PROTO interface
      // when they are read in again later anyways. -- 20040115 larsa
      return FALSE;
    }
#endif // disabled PROTO hack
    return TRUE;
  }

  // SGI Inventor seems to test forward connections here also. We
  // consider this is bug, since this field should not write just
  // because some field is connected from this field.  pederb.

  return FALSE;
}

/*!
  Called whenever another slave attaches or detaches itself to us.  \a
  numconnections is the difference in number of connections made
  (i.e. if stuff is \e disconnected, \a numconnections will be a
  negative number).

  The default method is empty. Override in subclasses if you want do
  something special on connections/deconnections.
*/
void
SoField::connectionStatusChanged(int COIN_UNUSED_ARG(numconnections))
{
}

/*!
  Returns \c TRUE if this field should not be written into at the
  moment the method is called.

  This method is used internally in Coin during notification and
  evaluation processes, and should normally not be of interest to the
  application programmer.
*/
SbBool
SoField::isReadOnly(void) const
{
  return this->getStatus(FLAG_READONLY);
}

/*!
  This method is internally called after SoField::copyFrom() during
  scene graph copies, and should do the operations necessary for
  fixing up the field instance after it has gotten a new value.

  The default method in the SoField superclass does nothing.

  The application programmer should normally not need to consider this
  method, unless he constructs a complex field type which contains new
  references to container instances (i.e. nodes or
  engines). Overriding this method is then necessary to update the
  reference pointers, as they could have been duplicated during the
  copy operation.
*/
void
SoField::fixCopy(SbBool COIN_UNUSED_ARG(copyconnections))
{
}

/*!
  Returns \c TRUE if this field has references to any containers in
  the scene graph which are also duplicated during the copy operation.

  Note that this method \e only is valid to call during copy
  operations.

  See also the note about the relevance of the fixCopy() method for
  application programmers, as it is applicable on this method aswell.
*/
SbBool
SoField::referencesCopy(void) const
{
  int i, n;
  if (!this->hasExtendedStorage()) return FALSE;

  const SoFieldList & masterfields = this->storage->masterfields;
  n = masterfields.getLength();
  for (i = 0; i < n; i++) {
    SoFieldContainer * fc = masterfields[i]->getContainer();
    if (SoFieldContainer::checkCopy(fc)) return TRUE;
  }

  const SoEngineOutputList & masterengineouts =
    this->storage->masterengineouts;
  n = masterengineouts.getLength();
  for (i = 0; i < n; i++) {
    SoEngineOutput * eout = masterengineouts[i];
    SbBool isengine = ! eout->isNodeEngineOutput();
    SoFieldContainer * fc = isengine ?
      coin_assert_cast<SoFieldContainer *>(eout->getContainer()) :
      coin_assert_cast<SoFieldContainer *>(eout->getNodeContainer());
    if (SoFieldContainer::checkCopy(fc)) return TRUE;
    if (isengine || (fc->isOfType(SoEngine::getClassTypeId()) &&
                     coin_assert_cast<SoEngine *>(fc)->shouldCopy())) return TRUE;
  }
  return FALSE;
}

/*!
  If \a fromfield contains a connection to another field, make this
  field also use the same connection.
*/
void
SoField::copyConnection(const SoField * fromfield)
{
  // Consider most common case first.
  if (!fromfield->isConnected()) return;

  // first, disconnect all existing connections (engines often
  // connect to the realTime global field in the constructor).
  this->disconnect();

  assert(fromfield->hasExtendedStorage());
  int i;

  for (i = 0; i < fromfield->storage->masterfields.getLength(); i++) {
    SoField * master = fromfield->storage->masterfields[i];
    SoFieldContainer * masterfc = master->getContainer();
    SbName fieldname;
    (void) masterfc->getFieldName(master, fieldname);
    SoFieldContainer * copyfc = masterfc->copyThroughConnection();
    SoField * copyfield = copyfc->getField(fieldname);

    SbBool notnotify = FALSE;
    switch (master->getFieldType()) {
    case EVENTIN_FIELD:
    case EVENTOUT_FIELD:
      notnotify = TRUE;
      break;
    default:
      break;
    }
    (void) this->connectFrom(copyfield, notnotify, TRUE);
  }
  for (i = 0; i < fromfield->storage->masterengineouts.getLength(); i++) {
    SoEngineOutput * master = fromfield->storage->masterengineouts[i];
    SoEngineOutput * copyeo = NULL;

    if (master->isNodeEngineOutput()) {
      SbName name;
      SoNodeEngine * masterengine = master->getNodeContainer();
      (void) masterengine->getOutputName(master, name);
      SoNodeEngine * copyengine =
       coin_assert_cast<SoNodeEngine *>(masterengine->copyThroughConnection());
      copyeo = copyengine->getOutput(name);
    }
    else {
      SbName name;
      SoEngine * masterengine = master->getContainer();
      (void) masterengine->getOutputName(master, name);
      SoEngine * copyengine =
       coin_assert_cast<SoEngine *>(masterengine->copyThroughConnection());
      copyeo = copyengine->getOutput(name);
    }
    assert(copyeo);
    (void) this->connectFrom(copyeo, FALSE, TRUE);
  }
}

// This templatized inline is just a convenience function for reading
// with error detection.
template <class Type>
static inline SbBool
READ_VAL(SoInput * in, Type & val)
{
  if (!in->read(val)) {
    SoReadError::post(in, "Premature end of file");
    return FALSE;
  }
  return TRUE;
}


/*!
  Reads and sets the value of this field from the given SoInput
  instance.  Returns \c FALSE if the field value can not be parsed
  from the input.

  The second argument is the field's context-specific \a name, which
  is typically its unique identifier in its field container.

  \sa set(), write()
*/
SbBool
SoField::read(SoInput * in, const SbName & name)
{
  SbBool readok = TRUE;
  SbBool oldnotify = this->enableNotify(FALSE);
  SbBool didreadvalue = FALSE;

  if (in->checkISReference(this->getContainer(), name, readok) || readok == FALSE) {
    if (!readok) {
      SoFieldContainer * fc = this->getContainer();
      SbString s("");
      if (fc) { s.sprintf(" of %s", fc->getTypeId().getName().getString()); }
      SoReadError::post(in, "Couldn't read value for field \"%s\"%s",
                        name.getString(), s.getString());
    }
    goto sofield_read_return;
  }

  this->setDefault(FALSE);
  this->setDirty(FALSE);

  if (!in->isBinary()) { // ASCII file format.
    char c;
    // Check for the ignored flag first, as it is valid to let the
    // field data be just the ignored flag and nothing else.
    if (!READ_VAL(in, c)) { readok = FALSE; goto sofield_read_return; }

    if (c == IGNOREDCHAR) this->setIgnored(TRUE);
    else {
      // First check if there's a field-to-field connection here as
      // the default value following the field can be omitted.
      if (c == CONNECTIONCHAR) {
        // There's potential for an obscure bug to happen here: if the
        // field is an SoSFString where the string is unquoted and
        // starts with a CONNECTIONCHAR (i.e. '='), it will lead to a
        // false positive for the if()-check below, which again causes a
        // rather obtuse error message:
        //
        // Coin read error: Expected '{'; got '}'
        //     Occurred at line   3 in hepp.iv
        //
        // For the following test file:
        //
        // ----8<---- [snip] -------8<----
        // #Inventor V2.1 ascii
        //
        // Info { string =moo }
        // ----8<---- [snip] -------8<----
        //
        // Tamer Fahmy investigated and found this behavior to also
        // happen for SGI Inventor. Since that is the case, we won't
        // try to handle this as a valid file construct.
        //
        // FIXME: it would be nice if we could improve the error
        // message, to let the app programmer actually stand a chance
        // of debugging this when it happens. 20030811 mortene.
        if (!this->readConnection(in)) { readok = FALSE; goto sofield_read_return; }
        goto sofield_read_return;
      }
      else in->putBack(c);

      // Read field value(s).
      if (!this->readValue(in)) {
        SoFieldContainer * fc = this->getContainer();
        SbString s("");
        if (fc) { s.sprintf(" of %s", fc->getTypeId().getName().getString()); }
        SoReadError::post(in, "Couldn't read value for field \"%s\"%s",
                          name.getString(), s.getString());
        readok = FALSE;
        goto sofield_read_return;
      }
      else didreadvalue = TRUE;

      // Check again for the ignored flag indicator after the field
      // value.
      if (in->read(c)) { // if-check in case EOF on an SoField::set() invocation
        if (c == IGNOREDCHAR) this->setIgnored(TRUE);
        else in->putBack(c);
      }
    }

    // Check field-to-field connection indicator again /after/ the
    // field (start-)value.
    if (in->read(c)) { // if-check in case EOF on an SoField::set() invocation
      if (c == CONNECTIONCHAR) { if (!this->readConnection(in)) { readok = FALSE; goto sofield_read_return; } }
      else { in->putBack(c); }
    }
  }
  else { // Binary file format.
    // Read field value(s).
    if (!this->readValue(in)) {
      SoFieldContainer * fc = this->getContainer();
      SbString s("");
      if (fc) { s.sprintf(" of %s", fc->getTypeId().getName().getString()); }
      SoReadError::post(in, "Couldn't read value for field \"%s\"%s",
                        name.getString(), s.getString());
      readok = FALSE;
      goto sofield_read_return;
    }
    else didreadvalue = TRUE;

    // Check for the "ignored", "connection" and "default" flags.
    unsigned int flags;
    if (!READ_VAL(in, flags)) { readok = FALSE; goto sofield_read_return; }

    if (flags & SoField::IGNORED) this->setIgnored(TRUE);
    if (flags & SoField::CONNECTED) { if (!this->readConnection(in)) { readok = FALSE; goto sofield_read_return; }}
    if (flags & SoField::DEFAULT) this->setDefault(TRUE);

#if COIN_DEBUG
    if (flags & ~SoField::ALLFILEFLAGS) {
      SoDebugError::postWarning("SoField::read",
                                "unknown field flags (0x%x) -- "
                                "please report to <coin-support@coin3d.org>",
                                flags);
    }
#endif // COIN_DEBUG
  }

 sofield_read_return:
  (void) this->enableNotify(oldnotify);

  if (readok) {
    if (didreadvalue) this->valueChanged(FALSE);
    else {
      // we called setDirty(FALSE) in the beginning of the function.
      // Since this field is read without a value (just connected to
      // some other field/engine), we need to mark the field as dirty
      // so that it's evaluated the next time the field is read
      this->setDirty(TRUE);
      this->startNotify();
    }
  }
  return readok;
}

/*!
  Write the value of the field to the given SoOutput instance (which
  can be either a memory buffer or a file, in ASCII or in binary
  format).

  \sa get(), read(), SoOutput
*/
void
SoField::write(SoOutput * out, const SbName & name) const
{
  if (out->getStage() == SoOutput::COUNT_REFS) {
    // Handle first stage of write operations.
    this->countWriteRefs(out);
    return;
  }

  // Ok, we've passed the first write stage and is _really_ writing.

  // Check connection (this is common code for ASCII and binary
  // write).
  SbBool writeconnection = FALSE;
  SbName dummy;
  SoFieldContainer * fc = this->resolveWriteConnection(dummy);

  if (fc && (SoWriterefCounter::instance(out)->shouldWrite(fc) || fc->isOfType(SoEngine::getClassTypeId())))
    writeconnection = TRUE;

  // check VRML2 connections. Since VRML2 fields can have multiple
  // master fields/engines, the field can still be default even though
  // it is connected, and we should _not_ write the field. The ROUTEs
  // should be added though. pederb, 2002-06-13

  if (is_vrml2_field(this)) {
    if (writeconnection) {
      writeconnection = FALSE;
      this->storage->add_vrml2_routes(out, this);
      // if no value has been set, don't write field even if it's
      // connected
      if (this->isDefault()) return;
    }
    // never write eventIn or eventOut fields
    if ((this->getFieldType() == SoField::EVENTIN_FIELD) ||
        (this->getFieldType() == SoField::EVENTOUT_FIELD)) return;
  }

  // ASCII write.
  if (!out->isBinary()) {
    out->indent();
    // Cast to avoid "'s.
    out->write(static_cast<const char *>(name));
    if (!this->isDefault()) {
      out->write(' ');
      this->writeValue(out);
    }
    if (this->isIgnored()) {
      out->write(' ');
      out->write(IGNOREDCHAR);
    }

    if (writeconnection) this->writeConnection(out);
    out->write('\n');
  }
  // Binary write.
  else {
    // Cast to avoid "'s.
    out->write(static_cast<const char *>(name));
    this->writeValue(out);

    unsigned int flags = 0;
    if (this->isIgnored()) flags |= SoField::IGNORED;
    if (writeconnection) flags |= SoField::CONNECTED;
    if (this->isDefault()) flags |= SoField::DEFAULT;

    out->write(flags);

    if (writeconnection) this->writeConnection(out);
  }
}

#include <cstdio>

/*!
  This method is called during the first pass of write operations, to
  count the number of write references to this field and to "forward"
  the reference counting operation to the field containers we're
  connected to.
*/
void
SoField::countWriteRefs(SoOutput * out) const
{
  // Count all connected fields/engines. Inventor only allows one
  // master field/engine, but VRML2 can have multiple. This code
  // should work for both Inventor and VRML2 scene graphs
  // though. pederb, 2002-06-13
  if (this->isConnected()) {
    if (is_vrml2_field(this)) {
      this->storage->add_vrml2_routes(out, this);
    }
    else {
      int i;
      for (i = 0; i < this->storage->masterfields.getLength(); i++) {
        SoField * master = this->storage->masterfields[i];
        SoFieldContainer * fc = master->getContainer();
        assert(fc);
        // TRUE = reference is from field connection. This is needed
        // so that the fields inside 'fc' is counted only once
        fc->addWriteReference(out, TRUE);
      }
      for (i = 0; i < this->storage->masterengineouts.getLength(); i++) {
        SoEngineOutput * engineout = this->storage->masterengineouts[i];
        SoFieldContainer * fc = engineout->getFieldContainer();
        assert(fc);
        // since engines are always connected directly to the field
        // (they're not nodes), engines are always counted with
        // isfromfield = FALSE
        fc->addWriteReference(out, FALSE);
      }
    }
  }
}

/*!
  \fn void SoField::evaluate(void) const

  Re-evaluates the value of this field any time a getValue() call is
  made and the field is marked dirty. This is done in this way to gain
  the advantages of having lazy evaluation.
*/

//
// private method called from SoField::evaluate() when the field is
// connected and dirty
//
void
SoField::evaluateField(void) const
{
  // if we're destructing, don't continue as this would cause
  // a call to the virtual evaluateConnection()
  if (this->getStatus(FLAG_ISDESTRUCTING)) {
#if COIN_DEBUG && 0 // debug
    SoDebugError::postInfo("SoField::evaluate",
                           "Stopped evaluate while destructing.");
#endif // debug
    return;
  }

  if (!this->isConnected()) return;

  assert(this->storage != NULL);

  // lock _before_ testing FLAG_ISEVALUATING to be thread safe
  SOFIELD_RECLOCK;
  // Recursive calls to SoField::evalute() should _absolutely_ not
  // happen, as the state of the field variables might not be
  // consistent while evaluating.
  //
  // This is an error which is not too hard to bump into, and the
  // _immediate_ repercussions are non-fatal, so we just spit out this
  // error message and carry on -- to not cause any more application
  // programmer frustrations than necessary.

  if (this->getStatus(FLAG_ISEVALUATING)) {
#if COIN_DEBUG
    SoDebugError::post("SoField::evaluate",
                       "Detected indirectly recursive call to "
                       "SoField::evaluate() -- which is a *bad* thing."
                       "This indicates a non-trivial programming error "
                       "somewhere either in the application (most likely) "
                       "or the library code itself (less likely). "
                       "We strongly advise you to investigate and resolve "
                       "this issue before moving on.");
#endif // COIN_DEBUG
    SOFIELD_RECUNLOCK;
    return;
  }

  // Cast away the const. (evaluate() must be const, since we're using
  // evaluate() from getValue().)
  SoField * that = const_cast<SoField *>(this);

  // Check the NEEDEVALUATION flag in case some other thread has just
  // evaluated the field. The flag is checked in SoField::evaluate(),
  // but it is possible that two (or more) threads might enter
  // evaluateField() simultaneously, so this test is necessary.
  // pederb, 2002-10-04
  if (this->getStatus(FLAG_NEEDEVALUATION) && this->getStatus(FLAG_ENABLECONNECTS)) {
    that->setStatusBits(FLAG_ISEVALUATING);
    this->evaluateConnection();
    that->clearStatusBits(FLAG_ISEVALUATING);
    // this will clear the NEEDEVALUATION flag
    that->setDirty(FALSE);
  }
  SOFIELD_RECUNLOCK;
}

/*!
  Do we need re-evaluation?
*/
SbBool
SoField::getDirty(void) const
{
  return this->getStatus(FLAG_NEEDEVALUATION);
}

/*!
  Mark field for re-evaluation (upon next read operation), but do not
  trigger a notification.
*/
void
SoField::setDirty(SbBool dirty)
{
  (void) this->changeStatusBits(FLAG_NEEDEVALUATION, dirty);
}

/*!
  Connect ourself as slave to another object, while still keeping the
  other connections currently in place.

  \sa connectFrom()
*/
SbBool
SoField::appendConnection(SoEngineOutput * master, SbBool notnotify)
{
  return this->connectFrom(master, notnotify, TRUE);
}

/*!
  Connect ourself as slave to another object, while still keeping the
  other connections currently in place.

  \sa connectFrom()
*/
SbBool
SoField::appendConnection(SoField * master, SbBool notnotify)
{
  return this->connectFrom(master, notnotify, TRUE);
}

// Make a converter from value(s) of the given field type and the
// value(s) of this type. Returns NULL if no value conversion between
// types is possible.
SoFieldConverter *
SoField::createConverter(SoType from) const
{
  SoType thistype = this->getTypeId();
  assert(from != thistype);
  SoType convtype = SoDB::getConverter(from, thistype);
  if (convtype == SoType::badType()) {
#if COIN_DEBUG // COIN_DEBUG
    SoDebugError::postWarning("SoField::createConverter",
                              "no converter for %s to %s",
                              from.getName().getString(),
                              thistype.getName().getString());
#endif // COIN_DEBUG
    return NULL;
  }

  SoFieldConverter * fc;

  if (convtype == SoConvertAll::getClassTypeId())
    fc = new SoConvertAll(from, this->getTypeId());
  else
    fc = static_cast<SoFieldConverter *>(convtype.createInstance());

  fc->ref();
  return fc;
}


/*!
  Read the master field of a field-to-field connection (and its field
  container).

  If input parsing is successful, this field will be connected as a
  slave to the master field.

  Note that this slave field will \e not be marked as "dirty" upon
  connection, i.e. it will retain its value until the first update of
  the master field is made \e after the connection was set up. This to
  be in conformance with how the Inventor Mentor specifies how field
  connections should be imported (see page 270).
*/
SbBool
SoField::readConnection(SoInput * in)
{
  // For debugging purposes, here's a handy test case for checking
  // that a field-field connection, where an initial value for the
  // slave is given, will behave according to the Mentor, as mentioned
  // above in the function API documentation:
  //
  // -----8<------- [snip] -----------------8<------- [snip] -----------
  // #Inventor V2.1 ascii
  //
  // DEF SCENE_ROOT Separator {
  //    ## on startup this should give a green cube
  //    Switch {
  //       whichChild 0 = SelectOne { type SoMFInt32 index 1 input [ 0,1 ] }.output
  //       Material { diffuseColor 0.1 1.0 0.1 }
  //       Material { diffuseColor 1.0 0.1 0.1 }
  //    }
  //    Cone {}
  // } # SCENE_ROOT
  // -----8<------- [snip] -----------------8<------- [snip] -----------
  //
  // (Provided by Gerhard Reitmayr.)

  // ***********************************************************************

  // Read the fieldcontainer instance containing the master field
  // we're connected to.
  SoBase * bp;
  if (!SoBase::read(in, bp, SoFieldContainer::getClassTypeId())) return FALSE;
  if (!bp) {
    SoReadError::post(in, "couldn't read field-to-field connection");
    return FALSE;
  }

  SoFieldContainer * fc = coin_assert_cast<SoFieldContainer *>(bp);

  // Scan past the '.' character for ASCII format.
  if (!in->isBinary()) {
    char c;
    if (!in->read(c)) {
      SoReadError::post(in, "premature EOF");
      return FALSE;
    }
    if (c != '.') {
      SoReadError::post(in, "expected field connection token '.', "
                        "but got '%c'", c);
      return FALSE;
    }
  }

  // Read name of master field.
  SbName mastername;
  if (!in->read(mastername, TRUE)) {
    SoReadError::post(in, "premature EOF");
    return FALSE;
  }

  // Get pointer to master field or engine output and connect.

  SoEngineOutput * masteroutput = NULL;
  SoField * masterfield = fc->getField(mastername);

  if (!masterfield) {
    masteroutput =
      fc->isOfType(SoEngine::getClassTypeId()) ?
      coin_safe_cast<SoEngine*>(fc)->getOutput(mastername) : NULL;

    if (!masteroutput) {
      masteroutput =
        fc->isOfType(SoNodeEngine::getClassTypeId()) ?
        coin_safe_cast<SoNodeEngine *>(fc)->getOutput(mastername) : NULL;
    }
  }

  if (!masterfield && !masteroutput) {
    SoReadError::post(in, "no field or output ``%s'' in ``%s''",
                      mastername.getString(),
                      fc->getTypeId().getName().getString());
    return FALSE;
  }

  SbBool ok = FALSE;

  // Make connection, with "do not notify" flag set to TRUE, to avoid
  // making ourselves "dirty" (i.e.: we will continue using our
  // current value until the master is updated).
  if (masterfield) { ok = this->connectFrom(masterfield, TRUE); }
  else if (masteroutput) { ok = this->connectFrom(masteroutput, TRUE); }

  if (!ok) {
    SoReadError::post(in, "couldn't connect ``%s'' field to ``%s'', "
                      "connection will be ignored",
                      this->getTypeId().getName().getString(),
                      mastername.getString());
  }

  return TRUE;
}

/*!
  Write out information about this field's connection.
*/
void
SoField::writeConnection(SoOutput * out) const
{
  SbName mastername;
  SoFieldContainer * fc = this->resolveWriteConnection(mastername);
  assert(fc);

  if (!out->isBinary()) {
    out->write(' ');
    out->write(CONNECTIONCHAR);
  }

  if (fc->isOfType(SoNode::getClassTypeId())) {
    SoWriteAction wa(out);
    wa.continueToApply(coin_assert_cast<SoNode *>(fc));
  }
  else {
    // Note: for this to work, classes inheriting SoFieldContainer
    // which are _not_ also inheriting from SoNode must call
    // SoBase::writeHeader() and SoBase::writeFooter().
    fc->writeInstance(out);
    // FIXME: does this work for engines? 20000131 mortene.
  }

  if (!out->isBinary()) {
    out->indent();
    out->write(". ");
  }

  out->write(mastername.getString());
}

// Check if this field should write a connection upon export. Returns
// a pointer to the fieldcontainer with the master field we're
// connected to (or NULL if none, or if the master field's container
// is not within the scenegraph). If the return value is non-NULL, the
// name of the master field is copied to the mastername argument.
SoFieldContainer *
SoField::resolveWriteConnection(SbName & mastername) const
{
  if (!this->isConnected()) return NULL;

  SoFieldContainer * fc = NULL;
  SoField * fieldmaster;
  SoEngineOutput * enginemaster;

  if (this->getConnectedField(fieldmaster)) {
    fc = fieldmaster->getContainer();
    assert(fc);
    SbBool ok = fc->getFieldName(fieldmaster, mastername);
    assert(ok);
  }
  else if (this->getConnectedEngine(enginemaster)) {
    fc = enginemaster->getFieldContainer();
    assert(fc);
    // FIXME: couldn't we use getFieldName()? 20000129 mortene.
    SbBool ok =
      enginemaster->isNodeEngineOutput() ?
      coin_assert_cast<SoNodeEngine *>(fc)->getOutputName(enginemaster, mastername) :
      coin_assert_cast<SoEngine *>(fc)->getOutputName(enginemaster, mastername);
    assert(ok);
  }
  else assert(FALSE);

  return fc;
}


/*!
  If we're connected to a field/engine/interpolator, copy the value
  from the master source.
*/
void
SoField::evaluateConnection(void) const
{
  SbBool fanin = this->storage->hasFanIn();
  SbBool didevaluate = FALSE;

  // FIXME: should we evaluate from all masters in turn? 19990623 mortene.
  if (this->isConnectedFromField()) {
    int idx = fanin ? this->storage->findFanInField() : this->storage->masterfields.getLength() - 1;
    if (idx >= 0) {
      didevaluate = TRUE;
      SoField * master = this->storage->masterfields[idx];
      // don't copy if master is destructing, or if master is currently
      // evaluating. The master might be evaluating if we have circular
      // field connections. If this is the case, the field will already
      // contain the correct value, and we should not copy again.
      if (!master->isDestructing() && !master->getStatus(FLAG_ISEVALUATING)) {
        SoFieldConverter * converter = this->storage->findConverter(master);
        if (converter) converter->evaluateWrapper();
        else {
          SoField * that = const_cast<SoField *>(this); // cast away const
          // Copy data. Disable notification first since notification
          // has already been sent from the master.
          SbBool oldnotify = that->enableNotify(FALSE);
          that->copyFrom(*master);
          (void) that->enableNotify(oldnotify);
        }
      }
    }
  }
  if (this->isConnectedFromEngine() && !didevaluate) {
    int idx = fanin ? this->storage->findFanInEngine() : this->storage->masterengineouts.getLength() - 1;
    if (idx >= 0) {
      SoEngineOutput * master = this->storage->masterengineouts[idx];
      SoFieldConverter * converter = this->storage->findConverter(master);
      if (converter) converter->evaluateWrapper();
      else if (master->isNodeEngineOutput()) {
        master->getNodeContainer()->evaluateWrapper();
      }
      else {
        master->getContainer()->evaluateWrapper();
      }
    }
  }
}

/*!
  This method is always called whenever the field's value has been
  changed by direct invocation of setValue() or some such. You should
  \e never call this method from anywhere in the code where the field
  value is being set through an evaluation of its connections.

  If \a resetdefault is \c TRUE, the flag marking whether or not the
  field has its default value will be set to \c FALSE.

  The method will also notify any auditors that the field's value has
  changed.
*/
void
SoField::valueChanged(SbBool resetdefault)
{
  if (this->changeStatusBits(FLAG_READONLY, TRUE)) {
    this->setDirty(FALSE);
    if (resetdefault) this->setDefault(FALSE);
    if (this->container) this->startNotify();
    this->clearStatusBits(FLAG_READONLY);
  }
}

// Notify any auditors by marking them dirty - i.e. ready for
// re-evaluation.  Auditors include connected fields, sensors,
// containers (nodes/engines), ...
void
SoField::notifyAuditors(SoNotList * l)
{
#if COIN_DEBUG && 0 // debug
  SoDebugError::postInfo("SoField::notifyAuditors",
                         "field %p, list %p", this, l);
#endif // debug
  if (this->hasExtendedStorage() && this->storage->auditors.getLength())
    this->storage->auditors.notify(l);
}

/*!
  Set type of this field.

  The possible values for \a type is: 0 for ordinary fields, 1 for
  eventIn fields, 2 for eventOut fields, 3 for internal fields, 4 for
  VRML2 exposedField fields. There are also enum values in SoField.h.
*/
void
SoField::setFieldType(int type)
{
  this->clearStatusBits(FLAG_TYPEMASK);
  assert(type >=0 && type <= FLAG_TYPEMASK);
  this->setStatusBits(static_cast<unsigned int>(type));
}

/*!
  Return the type of this field.

  \sa setFieldType()
*/
int
SoField::getFieldType(void) const
{
  return this->statusbits & FLAG_TYPEMASK;
}

/*!
  Can be used to check if a field is being destructed.
*/
SbBool
SoField::isDestructing(void) const
{
  return this->getStatus(FLAG_ISDESTRUCTING);
}

/*!
  Initialize all the field classes.
*/
void
SoField::initClasses(void)
{
  SoSField::initClass();
  SoSFBox2s::initClass();
  SoSFBox2i32::initClass();
  SoSFBox2f::initClass();
  SoSFBox2d::initClass();
  SoSFBox3s::initClass();
  SoSFBox3i32::initClass();
  SoSFBox3f::initClass();
  SoSFBox3d::initClass();
  SoSFBool::initClass();
  SoSFColor::initClass();
  SoSFColorRGBA::initClass();
  SoSFDouble::initClass();
  SoSFEngine::initClass();
  SoSFFloat::initClass();
  SoSFShort::initClass();
  SoSFUShort::initClass();
  SoSFInt32::initClass();
  SoSFUInt32::initClass();
  SoSFVec2b::initClass();
  SoSFVec2s::initClass();
  SoSFVec2i32::initClass();
  SoSFVec2f::initClass();
  SoSFVec2d::initClass();
  SoSFVec3b::initClass();
  SoSFVec3s::initClass();
  SoSFVec3i32::initClass();
  SoSFVec3f::initClass();
  SoSFVec3d::initClass();
  SoSFVec4b::initClass();
  SoSFVec4ub::initClass();
  SoSFVec4s::initClass();
  SoSFVec4us::initClass();
  SoSFVec4i32::initClass();
  SoSFVec4ui32::initClass();
  SoSFVec4f::initClass();
  SoSFVec4d::initClass();
  SoSFMatrix::initClass();
  SoSFEnum::initClass();
  SoSFBitMask::initClass();
  SoSFImage::initClass();
  SoSFImage3::initClass();
  SoSFName::initClass();
  SoSFNode::initClass();
  SoSFPath::initClass();
  SoSFPlane::initClass();
  SoSFRotation::initClass();
  SoSFString::initClass();
  SoSFTime::initClass();
  SoSFTrigger::initClass();

  SoMField::initClass();
  SoMFBool::initClass();
  SoMFColor::initClass();
  SoMFColorRGBA::initClass();
  SoMFDouble::initClass();
  SoMFEngine::initClass();
  SoMFEnum::initClass();
  SoMFBitMask::initClass();
  SoMFFloat::initClass();
  SoMFInt32::initClass();
  SoMFMatrix::initClass();
  SoMFName::initClass();
  SoMFNode::initClass();
  SoMFPath::initClass();
  SoMFPlane::initClass();
  SoMFRotation::initClass();
  SoMFShort::initClass();
  SoMFString::initClass();
  SoMFTime::initClass();
  SoMFUInt32::initClass();
  SoMFUShort::initClass();
  SoMFVec2b::initClass();
  SoMFVec2s::initClass();
  SoMFVec2i32::initClass();
  SoMFVec2f::initClass();
  SoMFVec2d::initClass();
  SoMFVec3b::initClass();
  SoMFVec3s::initClass();
  SoMFVec3i32::initClass();
  SoMFVec3f::initClass();
  SoMFVec3d::initClass();
  SoMFVec4b::initClass();
  SoMFVec4ub::initClass();
  SoMFVec4s::initClass();
  SoMFVec4us::initClass();
  SoMFVec4i32::initClass();
  SoMFVec4ui32::initClass();
  SoMFVec4f::initClass();
  SoMFVec4d::initClass();

  // Create these obsoleted types for backwards compatibility. They
  // are typedef'ed to the types which obsoleted them, but this is
  // needed so it will also be possible to use SoType::fromName() with
  // the old names and create instances in that manner.
  //
  // FIXME: SoType::fromName("oldname") == SoType::fromName("newname")
  // will fail, but this can be solved with a hack in
  // SoType::operator==(). Do we _want_ to implement this hack,
  // though? It'd be ugly as hell.  19991109 mortene.
  // Does it need to be so ugly?  == could compare createInstance
  // pointers if both have is set?  But would it be correct, and would
  // any code depend on or benefit from such behaviour?  20070518 larsa
  SoType::createType(SoSField::getClassTypeId(), "SFLong",
                     &SoSFInt32::createInstance);
  SoType::createType(SoSField::getClassTypeId(), "SFULong",
                     &SoSFUInt32::createInstance);
  SoType::createType(SoMField::getClassTypeId(), "MFLong",
                     &SoMFInt32::createInstance);
  SoType::createType(SoMField::getClassTypeId(), "MFULong",
                     &SoMFUInt32::createInstance);
}

#undef FLAG_ALIVE_PATTERN
#undef SOFIELD_RECLOCK
#undef SOFIELD_RECUNLOCK