Source

Coin / src / misc / SoBase.cpp

Full commit
   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
/**************************************************************************\
 *
 *  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 SoBase SoBase.h Inventor/misc/SoBase.h
  \brief The SoBase class is the top-level superclass for a number
  of class-hierarchies.
  \ingroup general

  SoBase provides the basic interfaces and methods for doing reference
  counting, type identification and import/export. All classes in Coin
  which uses these mechanisms are descendent from this class.

  One important issue with SoBase-derived classes is that they should
  \e not be statically allocated, neither in static module memory nor
  on function's stack-frames. SoBase-derived classes must \e always be
  allocated dynamically from the memory heap with the \c new operator.

  This is so because SoBase-derived instances are reference counted,
  and will self-destruct on the approriate time. For this to work,
  they must be explicitly allocated in heap-memory. See the class
  documentation of SoNode for more information.
*/

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

// FIXME: There's a lot of methods in SoBase used to implement VRML
// support which are missing.
//
// UPDATE 20020217 mortene: is this FIXME still correct?

// FIXME: One more thing missing: detect cases where we should
// instantiate SoUnknownEngine instead of SoUnknownNode.

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

#include <Inventor/misc/SoBase.h>

#include <assert.h>
#include <string.h>

#include <Inventor/C/tidbits.h>
#include <Inventor/SoDB.h>
#include <Inventor/SoInput.h>
#include <Inventor/SoOutput.h>
#include <Inventor/engines/SoEngineOutput.h>
#include <Inventor/engines/SoNodeEngine.h>
#include <Inventor/errors/SoDebugError.h>
#include <Inventor/errors/SoReadError.h>
#include <Inventor/fields/SoField.h>
#include <Inventor/lists/SoBaseList.h>
#include <Inventor/lists/SoFieldList.h>
#include <Inventor/misc/SoProto.h>
#include <Inventor/misc/SoProtoInstance.h>
#include <Inventor/sensors/SoDataSensor.h>

#include "misc/SoBaseP.h"
#include "nodes/SoUnknownNode.h"
#include "fields/SoGlobalField.h"
#include "misc/SbHash.h"
#include "upgraders/SoUpgrader.h"
#include "threads/threadsutilp.h"
#include "tidbitsp.h"
#include "io/SoInputP.h"
#include "io/SoWriterefCounter.h"

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif // HAVE_CONFIG_H

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

// Note: the following documentation for getTypeId() will also be
// visible for subclasses, so keep it general.
/*!
  \fn SoType SoBase::getTypeId(void) const

  \brief Returns the type identification of an object derived from a
  class inheriting SoBase. This is used for run-time type checking and
  "downward" casting.

  Usage example:

  \code
  void foo(SoNode * node)
  {
    if (node->getTypeId() == SoFile::getClassTypeId()) {
      SoFile * filenode = (SoFile *)node;  // safe downward cast, knows the type
      /// [then something] ///
    }
  }
  \endcode


  For application programmers wanting to extend the library with new
  nodes, engines, nodekits, draggers or others: this method needs to
  be overridden in \e all subclasses. This is typically done as part
  of setting up the full type system for extension classes, which is
  usually accomplished by using the pre-defined macros available
  through for instance Inventor/nodes/SoSubNode.h (SO_NODE_INIT_CLASS
  and SO_NODE_CONSTRUCTOR for node classes),
  Inventor/engines/SoSubEngine.h (for engine classes) and so on.

  For more information on writing Coin extensions, see the class
  documentation of the toplevel superclasses for the various class
  groups.
*/

// Note: the following documentation for readInstance() will also be
// visible for subclasses, so keep it general.
/*!
  \fn SbBool SoBase::readInstance(SoInput * in, unsigned short flags)

  This method is mainly intended for internal use during file import
  operations.

  It reads a definition of an instance from the input stream \a in.
  The input stream state points to the start of a serialized /
  persistant representation of an instance of this class type.

  \c TRUE or \c FALSE is returned, depending on if the instantiation
  and configuration of the new object of this class type went ok or
  not.  The import process should be robust and handle corrupted input
  streams by returning \c FALSE.

  \a flags is used internally during binary import when reading user
  extension nodes, group nodes or engines.
*/

/*!
  \enum SoBase::BaseFlags
  \COININTERNAL
*/

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

SoType SoBase::classTypeId STATIC_SOTYPE_INIT;

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

// This can be any "magic" bitpattern of 4 bits which seems unlikely
// to be randomly assigned to a memory byte upon destruction. I chose
// "1101".
//
// The 4 bits allocated for the "alive" bitpattern is used in
// SoBase::ref() to try to detect when the instance has been
// prematurely destructed.
//
// <mortene@sim.no>
#define ALIVE_PATTERN 0xd

unsigned int SbHashFunc(const SoBase * key) {
  return SbHashFunc(reinterpret_cast<size_t>(key));
}

/*!
  Constructor. The initial reference count will be set to zero.
 */
SoBase::SoBase(void)
{
  // It is a common mistake to place e.g. nodes as static member
  // variables, or on the main()-function's stack-frame. This catches
  // some (but not all) of those cases.
  //
  // FIXME: we could probably add in an MSWin-specific extra check
  // here for instances placed dynamically on a stack, using Win32 API
  // functions that can classify a memory pointer as e.g. heap or
  // stack. 20031018 mortene.
  assert((SoBase::classTypeId != SoType::badType()) &&
         "An SoBase-derived class was attempted instantiated *before* Coin initialization. (Have you perhaps placed an SoBase-derived instance (e.g. a scene graph node) in non-heap memory?) See SoBase class documentation for more info.");

  cc_rbptree_init(&this->auditortree);

  this->objdata.referencecount = 0;

  // For debugging -- we try to catch dangling references after
  // premature destruction. See the SoBase::assertAlive() method for
  // further doc.
  this->objdata.alive = ALIVE_PATTERN;

  // For debugging, store a pointer to all SoBase-instances.
#if COIN_DEBUG
  if (SoBase::PImpl::trackbaseobjects) {
    CC_MUTEX_LOCK(SoBase::PImpl::allbaseobj_mutex);
    //void * dummy;
    assert(SoBase::PImpl::allbaseobj->find(this)==SoBase::PImpl::allbaseobj->const_end());
    (*SoBase::PImpl::allbaseobj)[this]=NULL;
    CC_MUTEX_UNLOCK(SoBase::PImpl::allbaseobj_mutex);
  }
#endif // COIN_DEBUG
}

/*!
  Destructor. There should not be any normal circumstance where you need
  to explicitly delete an object derived from the SoBase class, as the
  reference counting should take care of deallocating unused objects.

  \sa unref(), unrefNoDelete()
 */
SoBase::~SoBase()
{
#if COIN_DEBUG && 0 // debug
  SoDebugError::postInfo("SoBase::~SoBase", "%p", this);
#endif // debug

  // Set the 4 bits of bitpattern to anything but the "magic" pattern
  // used to check that we are still alive.
  this->objdata.alive = (~ALIVE_PATTERN) & 0xf;

  if (SoBase::PImpl::auditordict) {
    //SoAuditorList * l;
    if (SoBase::PImpl::auditordict->find(this)!=SoBase::PImpl::auditordict->const_end()) {
      SoBase::PImpl::auditordict->erase(this);
      //delete l;
    }
  }
  cc_rbptree_clean(&this->auditortree);

#if COIN_DEBUG
  if (SoBase::PImpl::trackbaseobjects) {
    CC_MUTEX_LOCK(SoBase::PImpl::allbaseobj_mutex);
    const SbBool ok = SoBase::PImpl::allbaseobj->erase(this);
    assert(ok && "something fishy going on in debug object tracking");
    CC_MUTEX_UNLOCK(SoBase::PImpl::allbaseobj_mutex);
  }
#endif // COIN_DEBUG
}

//
// callback from auditortree that is used to add sensor
// auditors to the list (closure).
//
static void
sobase_sensor_add_cb(void * auditor, void * type, void * closure)
{
  SbList<SoDataSensor *> * auditingsensors =
    (SbList<SoDataSensor*> *) closure;

  // MSVC7 on 64-bit Windows wants to go through this type when
  // casting from void*.
  const uintptr_t tmp = (uintptr_t)type;
  switch ((SoNotRec::Type) tmp) {
  case SoNotRec::SENSOR:
    auditingsensors->append((SoDataSensor *)auditor);
    break;

  case SoNotRec::FIELD:
  case SoNotRec::ENGINE:
  case SoNotRec::CONTAINER:
  case SoNotRec::PARENT:
    // FIXME: should any of these get special treatment? 20000402 mortene.
    break;

  default:
    assert(0 && "Unknown auditor type");
  }
}

/*!
  Cleans up all hanging references to and from this instance, and then
  commits suicide.

  Called automatically when the reference count goes to zero.
*/
void
SoBase::destroy(void)
{
  SbName name = this->getName();
#if COIN_DEBUG && 0 // debug
  SoType t = this->getTypeId();
  SoDebugError::postInfo("SoBase::destroy", "start -- %p '%s' ('%s')",
                         this, t.getName().getString(), name.getString());
#endif // debug


#if COIN_DEBUG
  if (SoBase::PImpl::tracerefs) {
    SoDebugError::postInfo("SoBase::destroy",
                           "%p ('%s')",
                           this, this->getTypeId().getName().getString());
  }
#endif // COIN_DEBUG

  // Find all auditors that they need to cut off their link to this
  // object. I believe this is necessary only for sensors.
  SbList<SoDataSensor *> auditingsensors;
  cc_rbptree_traverse(&this->auditortree, (cc_rbptree_traversecb *)sobase_sensor_add_cb, &auditingsensors);

  // Notify sensors that we're dying.
  for (int j = 0; j < auditingsensors.getLength(); j++)
    auditingsensors[j]->dyingReference();

  // Link out instance name from the list of all SoBase instances.
  if (name != SbName::empty()) SoBase::PImpl::removeName2Obj(this, name.getString());

#if COIN_DEBUG && 0 // debug
  SoDebugError::postInfo("SoBase::destroy", "delete this %p", this);
#endif // debug

  // Harakiri!
  delete this;

  // Link out obj-pointer to name reference now that object is dead.
  if (name != SbName::empty()) SoBase::PImpl::removeObj2Name(this, name.getString());

#if COIN_DEBUG && 0 // debug
  SoDebugError::postInfo("SoBase::destroy", "done -- %p '%s' ('%s')",
                         this, t.getName().getString(), name.getString());
#endif // debug
}

/*!
  \brief Sets up initialization for data common to all instances of
  this class, like submitting necessary information to the Coin type
  system.
 */
void
SoBase::initClass(void)
{
  // check_for_leaks() goes through the allocation list, and checks if
  // all allocated SoBase-derived instances was deallocated before the
  // atexit-routines were run.
  //
  // Set up to run after most other atexit-code, since we depend on
  // Coin cleaning up internal nodes etc (like the static
  // sub-scenegraphs in draggers).
  //
  // -mortene.
  coin_atexit((coin_atexit_f *)SoBase::PImpl::check_for_leaks, CC_ATEXIT_TRACK_SOBASE_INSTANCES);

  coin_atexit((coin_atexit_f *)SoBase::cleanClass, CC_ATEXIT_SOBASE);

  // Avoid multiple attempts at initialization.
  assert(SoBase::classTypeId == SoType::badType());

  SoBase::classTypeId = SoType::createType(SoType::badType(), "Base");

  SoBase::PImpl::name2obj = new SbHash<const char *, SbPList *>;
  SoBase::PImpl::obj2name = new SbHash<const SoBase *, const char *>();
  SoBase::PImpl::refwriteprefix = new SbString("+");
  SoBase::PImpl::allbaseobj = new SoBaseSet;

  CC_MUTEX_CONSTRUCT(SoBase::PImpl::mutex);
  CC_MUTEX_CONSTRUCT(SoBase::PImpl::obj2name_mutex);
  CC_MUTEX_CONSTRUCT(SoBase::PImpl::name2obj_mutex);
  CC_MUTEX_CONSTRUCT(SoBase::PImpl::allbaseobj_mutex);
  CC_MUTEX_CONSTRUCT(SoBase::PImpl::auditor_mutex);
  CC_MUTEX_CONSTRUCT(SoBase::PImpl::global_mutex);

  // debug
  const char * str = coin_getenv("COIN_DEBUG_TRACK_SOBASE_INSTANCES");
  SoBase::PImpl::trackbaseobjects = str && atoi(str) > 0;

  SoWriterefCounter::initClass();
}

// Clean up all commonly allocated resources before application
// exit. Only for debugging purposes.
void
SoBase::cleanClass(void)
{
  assert(SoBase::PImpl::name2obj);
  assert(SoBase::PImpl::obj2name);

  // Delete the SbPLists in the dictionaries.
  for(
      SbHash<const char *, SbPList *>::const_iterator iter =
       SoBase::PImpl::name2obj->const_begin();
      iter!=SoBase::PImpl::name2obj->const_end();
      ++iter
      ) {
    delete iter->obj;
  }

  delete SoBase::PImpl::allbaseobj; SoBase::PImpl::allbaseobj = NULL;

  delete SoBase::PImpl::name2obj; SoBase::PImpl::name2obj = NULL;
  delete SoBase::PImpl::obj2name; SoBase::PImpl::obj2name = NULL;

  delete SoBase::PImpl::refwriteprefix; SoBase::PImpl::refwriteprefix = NULL;

  SoBase::classTypeId STATIC_SOTYPE_INIT;

  CC_MUTEX_DESTRUCT(SoBase::PImpl::mutex);
  CC_MUTEX_DESTRUCT(SoBase::PImpl::obj2name_mutex);
  CC_MUTEX_DESTRUCT(SoBase::PImpl::allbaseobj_mutex);
  CC_MUTEX_DESTRUCT(SoBase::PImpl::name2obj_mutex);
  CC_MUTEX_DESTRUCT(SoBase::PImpl::auditor_mutex);
  CC_MUTEX_DESTRUCT(SoBase::PImpl::global_mutex);

  SoBase::PImpl::tracerefs = FALSE;
  SoBase::PImpl::writecounter = 0;
}

/*!
  \COININTERNAL

  There are 4 bits allocated for each SoBase-object for a bitpattern
  that indicates the object is still "alive". The pattern is changed
  when the object is destructed. If this method is then called after
  destruction, an assert will hit.

  This is used internally in Coin (in for instance SoBase::ref()) to
  try to detect when the instance has been prematurely
  destructed. This is a very common mistake to make by application
  programmers (letting the refcount dip to zero before it should, that
  is), so the extra piece of assistance through the accompanying
  assert() in this method to detect dangling references to the object,
  with subsequent memory corruption and mysterious crashes, should be
  a Good Thing.

  \COIN_FUNCTION_EXTENSION

  \since Coin 2.0
*/
void
SoBase::assertAlive(void) const
{
  if (this->objdata.alive != ALIVE_PATTERN) {
    SoDebugError::post("SoBase::assertAlive",
                       "Detected an attempt to access an instance (%p) of an "
                       "SoBase-derived class after it was destructed!  "
                       "This is most likely to be the result of some grave "
                       "programming error in the application / client "
                       "code (or less likely: internal library code), "
                       "causing premature destruction of a reference "
                       "counted object instance. This check was called "
                       "from a dangling reference to it.", this);
    assert(FALSE && "SoBase-object no longer alive!");
  }
}

/*!
  Increase the reference count of the object. This might be necessary
  to do explicitly from user code for certain situations (chiefly to
  avoid premature deletion), but is usually called from other instances
  within the Coin library when objects are made dependent on each other.

  See the class documentation of SoNode for more extensive information
  about reference counting.

  \sa unref(), unrefNoDelete()
 */
void
SoBase::ref(void) const
{
  if (COIN_DEBUG) this->assertAlive();

  CC_MUTEX_LOCK(SoBase::PImpl::mutex);
#if COIN_DEBUG
  int32_t currentrefcount = this->objdata.referencecount;
#endif // COIN_DEBUG
  this->objdata.referencecount++;
  CC_MUTEX_UNLOCK(SoBase::PImpl::mutex);

#if COIN_DEBUG
  if (this->objdata.referencecount < currentrefcount) {
    SoDebugError::post("SoBase::ref",
                       "%p ('%s') - referencecount overflow!: %d -> %d",
                       this, this->getTypeId().getName().getString(),
                       currentrefcount, this->objdata.referencecount);

    // The reference counter is contained within 27 bits of signed
    // integer, which means it can go up to about ~67 million
    // references. It's hard to imagine that this should be too small,
    // so we don't bother to try to handle overflows any better than
    // this.
    //
    // If we should ever revert this decision, look in Coin-1 for how
    // to handle overflows graciously.
    assert(FALSE && "reference count overflow");
  }
#endif // COIN_DEBUG

#if COIN_DEBUG
  if (SoBase::PImpl::tracerefs) {
    SoDebugError::postInfo("SoBase::ref",
                           "%p ('%s') - referencecount: %d",
                           this, this->getTypeId().getName().getString(),
                           this->objdata.referencecount);
  }
#endif // COIN_DEBUG
}

/*!
  Decrease the reference count of an object. If the reference count
  reaches zero, the object will delete itself. Be careful when
  explicitly calling this method, beware that you usually need to
  match user level calls to ref() with calls to either unref() or
  unrefNoDelete() to avoid memory leaks.

  \sa ref(), unrefNoDelete()
*/
void
SoBase::unref(void) const
{
  if (COIN_DEBUG) this->assertAlive();

  CC_MUTEX_LOCK(SoBase::PImpl::mutex);
  this->objdata.referencecount--;
  int refcount = this->objdata.referencecount;

  CC_MUTEX_UNLOCK(SoBase::PImpl::mutex);

#if COIN_DEBUG
  if (SoBase::PImpl::tracerefs) {
    SoDebugError::postInfo("SoBase::unref",
                           "%p ('%s') - referencecount: %d",
                           this, this->getTypeId().getName().getString(),
                           this->objdata.referencecount);
  }
  if (refcount < 0) {
    // Do the debug output in two calls, since the getTypeId() might
    // cause a crash, and then there'd be no output at all with a
    // single SoDebugError::postWarning() call.
    SoDebugError::postWarning("SoBase::unref", "ref count less than zero");
    SoDebugError::postWarning("SoBase::unref", "...for %s instance at %p",
                              this->getTypeId().getName().getString(), this);
  }
#endif // COIN_DEBUG
  if (refcount == 0) {
    SoBase * base = const_cast<SoBase *>(this);
    base->destroy();
  }
}

/*!
  Decrease reference count, but do \e not delete ourself if the count
  reaches zero.

  \sa unref()
 */
void
SoBase::unrefNoDelete(void) const
{
  if (COIN_DEBUG) this->assertAlive();

  this->objdata.referencecount--;
#if COIN_DEBUG
  if (SoBase::PImpl::tracerefs) {
    SoDebugError::postInfo("SoBase::unrefNoDelete",
                           "%p ('%s') - referencecount: %d",
                           this, this->getTypeId().getName().getString(),
                           this->objdata.referencecount);
  }
#endif // COIN_DEBUG
}

/*!
  Returns number of objects referring to this object.
*/
int32_t
SoBase::getRefCount(void) const
{
  return this->objdata.referencecount;
}

/*!
  Force an update, in the sense that all objects connected to this
  object as an auditor will have to re-check the values of their
  inter-dependent data.

  This is often used as an effective way of manually triggering a
  redraw by application programmers.
*/
void
SoBase::touch(void)
{
  this->startNotify();
}

/*!
  \brief Returns \c TRUE if the type of this object is either of the
  same type or inherited from \a type.

  This is used for run-time type checking and "downward" casting.

  Usage example:

  \code
  void foo(SoNode * node)
  {
    if (node->isOfType(SoGroup::getClassTypeId())) {
      SoGroup * group = (SoGroup *)node;  // safe downward cast, knows the type
      /// [then something ] ///
    }
  }
  \endcode

 */
SbBool
SoBase::isOfType(SoType type) const
{
  return this->getTypeId().isDerivedFrom(type);
}

/*!
  \brief This static method returns the SoType object associated with
  objects of this class.
 */
SoType
SoBase::getClassTypeId(void)
{
  return SoBase::classTypeId;
}

/*!
  Returns name of object. If no name has been given to this object,
  the returned SbName will contain the empty string.
 */
SbName
SoBase::getName(void) const
{
  // If this assert fails, SoBase::initClass() has probably not been
  // called, or you have objects on the stack that is destroyed after
  // you have invoked SoDB::cleanup().
  assert(SoBase::PImpl::obj2name);

  //const char * value = NULL;
  CC_MUTEX_LOCK(SoBase::PImpl::obj2name_mutex);
  SbHash<const SoBase *, const char *>::const_iterator tmp = SoBase::PImpl::obj2name->find(this);
  SbBool found = (tmp != SoBase::PImpl::obj2name->const_end());
  CC_MUTEX_UNLOCK(SoBase::PImpl::obj2name_mutex);
  return SbName(found ? tmp->obj : "");
}

/*!
  Set the name of this object.

  Some characters are invalid to use as parts of names for SoBase
  derived objects, as object names needs to be consistent with the
  syntax of Inventor and VRML files upon file export / import
  operations (so one must for instance avoid using special token
  characters).

  Invalid characters will be automatically replaced by underscore
  characters. If the name \e starts with an invalid character, the new
  name will be \e preceded by an underscore character.

  For the exact definitions of what constitutes legal and illegal
  characters for SoBase names, see the SbName functions listed below.

  \sa getName(), SbName::isBaseNameStartChar(), SbName::isBaseNameChar()
*/
void
SoBase::setName(const SbName & newname)
{

  // This may look peculiar, but it is useful in combination with the
  // COIN_DEBUG_TRACK_SOBASE_INSTANCES envvar to track down where
  // un-deallocated SoBase-instances were allocated from. (Ie run it
  // in a debugger and check the backtrace.)  -mortene.
#if 0 // debug
  static SbBool checked = FALSE;
  static const char * tracename = NULL;
  if (!checked) {
    tracename = coin_getenv("COIN_DEBUG_ASSERT_SOBASE_SETNAME");
    checked = TRUE;
  }
  if (tracename) { assert(newname != tracename); }
#endif // debug


  // remove old name first
  SbName oldName = this->getName();
  if (oldName != SbName::empty()) SoBase::removeName(this, oldName.getString());

  // semantics in the original SGI Inventor is to not build a separate
  // name list for unnamed SoBase instances
  if (newname == SbName::empty()) { return; }

  // check for bad characters
  const char * str = newname.getString();
  SbBool isbad = !SbName::isBaseNameStartChar(str[0]);

  int i;
  const int newnamelen = newname.getLength();
  for (i = 1; i < newnamelen && !isbad; i++) {
    isbad = !SbName::isBaseNameChar(str[i]);
  }

  if (isbad) {
    // replace bad characters
    SbString goodstring;

    if (!SbName::isBaseNameStartChar(str[0])) goodstring += '_';

    for (i = 0; i < newnamelen; i++) {
      goodstring += SbName::isBaseNameChar(str[i]) ? str[i] : '_';
    }

#if COIN_DEBUG
    SoDebugError::postWarning("SoBase::setName", "Bad characters in "
                              "name '%s'. Replacing with name '%s'",
                              str, goodstring.getString());
#endif // COIN_DEBUG

    SoBase::addName(this, SbName(goodstring.getString()));
  }
  else {
    SoBase::addName(this, newname.getString());
  }
}

/*!
  Adds a name<->object mapping to the global dictionary.
 */
void
SoBase::addName(SoBase * const b, const char * const name)
{
  assert(name);

  SbPList * l;
  CC_MUTEX_LOCK(SoBase::PImpl::name2obj_mutex);
  SbHash<const char*, SbPList*>::const_iterator tmp = SoBase::PImpl::name2obj->find(name);
  if (tmp==SoBase::PImpl::name2obj->const_end()) {
    // name not used before, create new list
    l = new SbPList;
    (*SoBase::PImpl::name2obj)[name] = l;
  }
  else {
    l = tmp->obj;
  }

  // append this to the list
  l->append(b);
  CC_MUTEX_UNLOCK(SoBase::PImpl::name2obj_mutex);

  CC_MUTEX_LOCK(SoBase::PImpl::obj2name_mutex);
  // set name of object. SbHash::put() will overwrite old name
  (*SoBase::PImpl::obj2name)[b] = name;
  CC_MUTEX_UNLOCK(SoBase::PImpl::obj2name_mutex);
}

/*!
  Removes a name<->object mapping from the global dictionary.
*/
void
SoBase::removeName(SoBase * const base, const char * const name)
{
  SoBase::PImpl::removeObj2Name(base, name);
  SoBase::PImpl::removeName2Obj(base, name);
}

/*!
  This is the method which starts the notification sequence
  after changes.

  At the end of a notification sequence, all "immediate" sensors
  (i.e. sensors set up with a zero priority) are triggered.
*/
void
SoBase::startNotify(void)
{
  SoNotList l;
  SoNotRec rec(createNotRec());
  l.append(&rec);
  l.setLastType(SoNotRec::CONTAINER);

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

/*!
  Notifies all auditors for this instance when changes are made.
*/
void
SoBase::notify(SoNotList * l)
{
  if (COIN_DEBUG) this->assertAlive();

#if COIN_DEBUG && 0 // debug
  SoDebugError::postInfo("SoBase::notify", "base %p, list %p", this, l);
#endif // debug

  SoBase::PImpl::NotifyData notdata;
  notdata.cnt = cc_rbptree_size(&this->auditortree);
  notdata.list = l;
  notdata.thisp = this;

  cc_rbptree_traverse(&this->auditortree, (cc_rbptree_traversecb *)SoBase::PImpl::rbptree_notify_cb, &notdata);
  assert(notdata.cnt == 0);
}

/*!
  Add an auditor to notify whenever the object changes in any significant
  way.

  \sa removeAuditor()
 */
void
SoBase::addAuditor(void * const auditor, const SoNotRec::Type type)
{
  // MSVC7 on 64-bit Windows wants to go through this type before
  // casting to void*.
  const uintptr_t val = (uintptr_t)type;
  cc_rbptree_insert(&this->auditortree, auditor, (void *)val);
}

/*!
  Remove an auditor from the list. \a auditor will then no longer be
  notified whenever any updates are made to this object.

  \sa addAuditor()
*/
void
SoBase::removeAuditor(void * const auditor, const SoNotRec::Type COIN_UNUSED_ARG(type))
{
  cc_rbptree_remove(&this->auditortree, auditor);
}


static void
sobase_audlist_add(void * pointer, void * type, void * closure)
{
  SoAuditorList * l = (SoAuditorList*) closure;
  // MSVC7 on 64-bit Windows wants to go through this type before
  // casting to void*.
  const uintptr_t tmp = (uintptr_t)type;
  l->append(pointer, (SoNotRec::Type)tmp);
}

/*!
  Returns list of objects auditing this object.

  \sa addAuditor(), removeAuditor()
*/
const SoAuditorList &
SoBase::getAuditors(void) const
{
  CC_MUTEX_LOCK(SoBase::PImpl::auditor_mutex);

  if (SoBase::PImpl::auditordict == NULL) {
    SoBase::PImpl::auditordict = new SbHash<const SoBase *, SoAuditorList *>();
    coin_atexit((coin_atexit_f*)SoBase::PImpl::cleanup_auditordict, CC_ATEXIT_NORMAL);
  }

  SoAuditorList * l = NULL;
  SbHash<const SoBase *, SoAuditorList *>::const_iterator iter
    = 
    SoBase::PImpl::auditordict->find(this);
  if (iter!=SoBase::PImpl::auditordict->const_end()) {
    l = iter->obj;
    // empty list before copying in new values
    for (int i = 0; i < l->getLength(); i++) {
      l->remove(i);
    }
  }
  else {
    (*SoBase::PImpl::auditordict)[this] = new SoAuditorList;
  }
  cc_rbptree_traverse(&this->auditortree, (cc_rbptree_traversecb*)sobase_audlist_add, (void*) l);

  CC_MUTEX_UNLOCK(SoBase::PImpl::auditor_mutex);

  return *l;
}

/*!
  This method is used during the first write pass of a write action to
  count the number of references to this object in the scene graph.
*/
void
SoBase::addWriteReference(SoOutput * out, SbBool isfromfield)
{
  assert(out->getStage() == SoOutput::COUNT_REFS);

  int refcount = SoWriterefCounter::instance(out)->getWriteref(this);

#if COIN_DEBUG
  if (SoWriterefCounter::debugWriterefs()) {
    SoDebugError::postInfo("SoBase::addWriteReference",
                           "%p/%s/'%s': %d -> %d",
                           this, this->getTypeId().getName().getString(),
                           this->getName().getString(),
                           refcount, refcount + 1);
  }
#endif // COIN_DEBUG

  refcount++;

  if (!isfromfield) {
    SoWriterefCounter::instance(out)->setInGraph(this, TRUE);
  }
  SoWriterefCounter::instance(out)->setWriteref(this, refcount);
}

/*!
  Returns \c TRUE if this object should be written out during a write action.
  Will return \c FALSE if no references to this object has been made in the
  scene graph.

  Note that connections from the fields of fieldcontainer objects is not
  alone a valid reason for writing out the object -- there must also be at
  least one reference directly from another SoBase (like a parent/child
  relationship, for instance).

  This method will return a valid result only during the second pass of
  write actions.
*/
SbBool
SoBase::shouldWrite(void)
{
  return SoWriterefCounter::instance(NULL)->shouldWrite(this);
}

/*!
  \COININTERNAL
*/
void
SoBase::incrementCurrentWriteCounter(void)
{
  ++SoBase::PImpl::writecounter;
}

/*!
  \COININTERNAL
*/
void
SoBase::decrementCurrentWriteCounter(void)
{
  --SoBase::PImpl::writecounter;
}

/*!
  Returns the object of \a type, or derived from \a type, registered
  under \a name. If several has been registered under the same name
  with the same type, returns the \e last one which was registered.

  If no object of a valid type or subtype has been registered with the
  given name, returns \c NULL.
*/
SoBase *
SoBase::getNamedBase(const SbName & name, SoType type)
{
  CC_MUTEX_LOCK(SoBase::PImpl::name2obj_mutex);
  SbHash<const char*, SbPList*>::const_iterator iter = 
    SoBase::PImpl::name2obj->find((const char *)name);
  if (iter!=SoBase::PImpl::name2obj->const_end()) {
    SbPList * l = iter->obj;
    if (l->getLength()) {
      SoBase * b = (SoBase *)((*l)[l->getLength() - 1]);
      if (b->isOfType(type)) {
        CC_MUTEX_UNLOCK(SoBase::PImpl::name2obj_mutex);
        return b;
      }
    }
  }
  CC_MUTEX_UNLOCK(SoBase::PImpl::name2obj_mutex);
  return NULL;
}

/*!
  Returns the number of objects of type \a type, or derived from \a type,
  registered under \a name.

  All matches will also be appended to \a baselist.
 */
int
SoBase::getNamedBases(const SbName & name, SoBaseList & baselist, SoType type)
{
  CC_MUTEX_LOCK(SoBase::PImpl::name2obj_mutex);

  int matches = 0;

  SbHash<const char*, SbPList*>::const_iterator iter = 
    SoBase::PImpl::name2obj->find((const char *)name);
  if (iter!=SoBase::PImpl::name2obj->const_end()) {
    SbPList * l = iter->obj;
    
    for (int i=0; i < l->getLength(); i++) {
      SoBase * b = (SoBase *)((*l)[i]);
      if (b->isOfType(type)) {
        baselist.append(b);
        matches++;
      }
    }
  }
  CC_MUTEX_UNLOCK(SoBase::PImpl::name2obj_mutex);

  return matches;
}

/*!
  Read next SoBase derived instance from the \a in stream, check that
  it is derived from \a expectedtype and place a pointer to the newly
  allocated instance in \a base.

  \c FALSE is returned on read errors, mismatch with the \a
  expectedtype, or if there are attempts at referencing (through the
  \c USE keyword) unknown instances.

  If we return \c TRUE with \a base equal to \c NULL, three things
  might have happened:

  1. End-of-file. Use SoInput::eof() after calling this method to
  detect end-of-file conditions.

  2. \a in didn't have a valid identifier name at the stream for us to
  read. This happens either in the case of errors, or when all child
  nodes of a group has been read. Check if the next character in the
  stream is a '}' to detect the latter case.

  3. A child was given as the \c NULL keyword. This can happen when
  reading the contents of SoSFNode fields (note that NULL is not
  allowed for SoMFNode)

  If \c TRUE is returned and \a base is not \c NULL upon return, the
  instance was allocated and initialized according to what was read
  from the \a in stream.
*/
SbBool
SoBase::read(SoInput * in, SoBase *& base, SoType expectedtype)
{
  // FIXME: the interface design for this function is goddamn _awful_!
  // We need to keep it like this, though, to be compatible with SGI
  // Inventor. What we however /could/ do about it is:
  //
  // First, split out the SoBase::PImpl class definition to a separate
  // interface, which can be accessed internally from Coin lirbary
  // code.
  //
  // Then, in this, write up /sensibly designed/ read()-function(s)
  // which implements the actually needed functionality of this
  // method.
  //
  // Third, make this function use those new functions in SoBase::PImpl (to
  // avoid code duplication) -- and mangle the results so that this
  // function still conforms to the SGI Inventor behavior.
  //
  // Finally, start using the SoBase::PImpl::read()-function(s) from
  // internal Coin code instead, to clean up the messy interaction
  // with this function from everywhere else.
  //
  // 20060202 mortene.

  assert(expectedtype != SoType::badType());
  base = NULL;

  SbName name;
  SbBool result = in->read(name, TRUE);

#if COIN_DEBUG
  if (SoInputP::debug()) {
    // This output is extremely useful when debugging the import code.
    SoDebugError::postInfo("SoBase::read",
                           "SoInput::read(&name, TRUE) => returns %s, name=='%s'",
                           result ? "TRUE" : "FALSE", name.getString());
  }
#endif // COIN_DEBUG

  // read all (vrml97) routes. Do this also for non-vrml97 files,
  // since in Coin we can have a mix of Inventor and VRML97 nodes in
  // the same file.
  while (result && name == PImpl::ROUTE_KEYWORD) {
    result = SoBase::readRoute(in);
    // read next ROUTE keyword
    if (result) result = in->read(name, TRUE);
    else return FALSE; // error while reading ROUTE
  }

  // The SoInput stream does not start with a valid base name. Return
  // TRUE with base==NULL.
  if (!result) return TRUE;

  // If no valid name / identifier string is found, the return value
  // from SbInput::read(SbName&,TRUE) _should_ also be FALSE.
  assert(name != "");

  if (name == PImpl::USE_KEYWORD) result = SoBase::PImpl::readReference(in, base);
  else if (name == PImpl::NULL_KEYWORD) return TRUE;
  else result = SoBase::PImpl::readBase(in, name, base);

  // Check type correctness.
  if (result) {
    assert(base);

    SoType type = base->getTypeId();
    assert(type != SoType::badType());

    if (!type.isDerivedFrom(expectedtype)) {
      SoReadError::post(in, "Type '%s' is not derived from '%s'",
                        type.getName().getString(),
                        expectedtype.getName().getString());
      result = FALSE;
    }
  }

  // Make sure we don't leak memory.
  if (!result && base && (name != PImpl::USE_KEYWORD)) {
    base->ref();
    base->unref();
  }

#if COIN_DEBUG
  if (SoInputP::debug()) {
    SoDebugError::postInfo("SoBase::read", "done, name=='%s' baseptr==%p, result==%s",
                           name.getString(), base, result ? "TRUE" : "FALSE");
  }
#endif // COIN_DEBUG

  return result;
}

/*!
  Referenced instances of SoBase are written as "DEF NamePrefixNumber" when
  exported. "Name" is the name of the base instance from setName(), "Prefix"
  is common for all objects and can be set by this method (default is "+"),
  and "Number" is a unique id which is necessary if multiple objects have
  the same name.

  If you want the prefix to be something else than "+", use this method.
 */
void
SoBase::setInstancePrefix(const SbString & c)
{
  SoWriterefCounter::setInstancePrefix(c);
  (*SoBase::PImpl::refwriteprefix) = c;
}

/*!
  Set to \c TRUE to activate debugging of reference counting, which
  could aid in finding hard to track down problems with accesses to
  freed memory or memory leaks. Note: this will produce lots of
  debug information in any "normal" running system, so use sensibly.

  The reference tracing functionality will be disabled in "release
  versions" of the Coin library.
 */
void
SoBase::setTraceRefs(SbBool trace)
{
  SoBase::PImpl::tracerefs = trace;
}

/*!
  Return the status of the reference tracing flag.

  \sa setTraceRefs()
 */
SbBool
SoBase::getTraceRefs(void)
{
  return SoBase::PImpl::tracerefs;
}

/*!
  Returns \c TRUE if this object will be written more than once upon
  export. Note that the result from this method is only valid during the
  second pass of a write action (and partly during the COUNT_REFS pass).
 */
SbBool
SoBase::hasMultipleWriteRefs(void) const
{
  return SoWriterefCounter::instance(NULL)->getWriteref(this) > 1;
}

// FIXME: temporary bug-workaround needed to test if we are exporting
// a VRML97 or an Inventor file. Implementation in SoOutput.cpp.
// pederb, 2003-03-18
extern SbString SoOutput_getHeaderString(const SoOutputP * out);

/*!
  Write out the header of any SoBase derived object. The header consists
  of the \c DEF keyword and the object name (if the object has a name,
  otherwise these will be skipped), the class name and a left bracket.

  Alternatively, the object representation may be made up of just the
  \c USE keyword plus the object name, if this is the second or subsequent
  reference written to the file.

  If the object has been completed just by writing the header (which will
  be the case if we're writing multiple references of an object),
  we return \c TRUE, otherwise \c FALSE.

  If we return \c FALSE (i.e. there's more to write), we will
  increment the indentation level.

  \sa writeFooter(), SoOutput::indent()
 */
SbBool
SoBase::writeHeader(SoOutput * out, SbBool isgroup, SbBool isengine) const
{
  if (!out->isBinary()) {
    out->write(PImpl::END_OF_LINE);
    out->indent();
  }

  SbName name = this->getName();
  int refid = out->findReference(this);
  SbBool firstwrite = (refid == SoWriterefCounter::FIRSTWRITE);
  SbBool multiref = SoWriterefCounter::instance(out)->hasMultipleWriteRefs(this);
  SbName writename = SoWriterefCounter::instance(out)->getWriteName(this);

  // Write the node
  if (!firstwrite) {
    out->write(PImpl::USE_KEYWORD);
    if (!out->isBinary()) out->write(' ');
    out->write(writename.getString());

    if (SoWriterefCounter::debugWriterefs()) {
      SbString tmp;
      tmp.sprintf(" # writeref: %d\n",
                  SoWriterefCounter::instance(out)->getWriteref(this));
      out->write(tmp.getString());
    }
  }
  else {
    if (name != SbName::empty() || multiref) {
      out->write(PImpl::DEF_KEYWORD);
      if (!out->isBinary()) out->write(' ');

      out->write(writename.getString());
      if (!out->isBinary()) out->write(' ');
    }

    if (this->isOfType(SoNode::getClassTypeId()) &&
        ((SoNode*)this)->getNodeType() == SoNode::VRML2) {
      SbString nodename(this->getFileFormatName());
      if (nodename.getLength() > 4) {
        SbString vrml = nodename.getSubString(0, 3);
        const char vrml2headerprefix[] = "#VRML V2.0 utf8";
        const size_t len = sizeof(vrml2headerprefix) - 1;
        const SbString fullheader = SoOutput_getHeaderString(out->pimpl);
        const SbString fileid = ((size_t)fullheader.getLength() < len) ?
          fullheader : fullheader.getSubString(0, len - 1);
        // FIXME: using a temporary workaround to test if we're
        // exporting a VRML97 file. pederb, 2003-03-18
        //
        // UPDATE 20060207 mortene: a better solution would be to
        // carry along the format information in the SoOutput (or an
        // internal private SoOutputP class?) as an enum or something,
        // methinks.
        if ((vrml == "VRML") && (fileid == vrml2headerprefix)) {
          SbString substring = nodename.getSubString(4);
          out->write(substring.getString());
        }
        else {
          out->write(nodename.getString());
        }
      }
      else {
        out->write(nodename.getString());
      }
    }
    else {
      out->write(this->getFileFormatName());
    }
    if (out->isBinary()) {
      unsigned int flags = 0x0;
      if (isgroup) flags |= SoBase::IS_GROUP;
      if (isengine) flags |= SoBase::IS_ENGINE;
      out->write(flags);
    }
    else {
      out->write(" {");
      if (SoWriterefCounter::debugWriterefs()) {
        SbString tmp;
        tmp.sprintf(" # writeref: %d\n",
                    SoWriterefCounter::instance(out)->getWriteref(this));
        out->write(tmp.getString());
      }
      out->write(PImpl::END_OF_LINE);
      out->incrementIndent();
    }
  }

  int writerefcount = SoWriterefCounter::instance(out)->getWriteref(this);

#if COIN_DEBUG
  if (SoWriterefCounter::debugWriterefs()) {
    SoDebugError::postInfo("SoBase::writeHeader",
                           "%p/%s/'%s': %d -> %d",
                           this,
                           this->getTypeId().getName().getString(),
                           this->getName().getString(),
                           writerefcount, writerefcount - 1);
  }
#endif // COIN_DEBUG

  writerefcount--;
  SoWriterefCounter::instance(out)->setWriteref(this, writerefcount);

  // Don't need to write out the rest if we are writing anything but
  // the first instance.
  return (firstwrite == FALSE);
}

/*!
  This method will terminate the block representing an SoBase derived
  object.
 */
void
SoBase::writeFooter(SoOutput * out) const
{
  if (!out->isBinary()) {

    // Keep the old ugly-bugly formatting style around, in case
    // someone, for some obscure reason, needs it.
    static int oldstyle = -1;
    if (oldstyle == -1) {
      oldstyle = coin_getenv("COIN_OLDSTYLE_FORMATTING") ? 1 : 0;
    }

    // FIXME: if we last wrote a field, this EOF is superfluous -- so
    // we are getting a lot of empty lines in the files. Should
    // improve output formatting further. 20031223 mortene.
    if (!oldstyle) { out->write(PImpl::END_OF_LINE); }

    out->decrementIndent();
    out->indent();
    out->write(PImpl::CLOSE_BRACE);
  }
}

/*!
  Returns the class name this object should be written under.  Default
  string returned is the name of the class from the type system.

  User extensions nodes and engines override this method to return the
  name of the extension (instead of "UnknownNode" or "UnknownEngine").
 */
const char *
SoBase::getFileFormatName(void) const
{
  return this->getTypeId().getName().getString();
}

/*!
  \COININTERNAL
*/
uint32_t
SoBase::getCurrentWriteCounter(void)
{
  return SoBase::PImpl::writecounter;
}

/*!
  Connect a route from the node named \a fromnodename's field \a
  fromfieldname to the node named \a tonodename's field \a
  tofieldname. This method will consider the fields types (event in,
  event out, etc) when connecting.

  \COIN_FUNCTION_EXTENSION

  \since Coin 2.0
*/
SbBool
SoBase::connectRoute(SoInput * COIN_UNUSED_ARG(in),
                     const SbName & fromnodename, const SbName & fromfieldname,
                     const SbName & tonodename, const SbName & tofieldname)
{
  SoNode * fromnode = SoNode::getByName(fromnodename);
  SoNode * tonode = SoNode::getByName(tonodename);
  if (fromnode && tonode) {
    SoDB::createRoute(fromnode, fromfieldname.getString(),
                      tonode, tofieldname.getString());
    return TRUE;
  }
  return FALSE;
}

/*!
  \COININTERNAL

  Reads a (VRML97) ROUTE. We decided to also add support for routes in
  Coin, as a generic feature, since we think it is nicer than setting
  up field connections inside the nodes.

*/
SbBool
SoBase::readRoute(SoInput * in)
{
  SbString fromstring, tostring;

  SbName fromnodename;
  SbName fromfieldname;
  SbName toname;
  SbName tonodename;
  SbName tofieldname;
  SbBool ok;

  ok =
    in->read(fromstring) &&
    in->read(toname) &&
    in->read(tostring);

  if (ok) ok = (toname == SbName("TO"));

  if (ok) {
    ok = FALSE;

    // parse from-string
    char * str1 = (char*) fromstring.getString();
    char * str2 = str1 ? (char*) strchr(str1, '.') : NULL;
    if (str1 && str2) {
      *str2++ = 0;

      // now parse to-string
      fromnodename = str1;
      fromfieldname = str2;
      str1 = (char*) tostring.getString();
      str2 = str1 ? strchr(str1, '.') : NULL;
      if (str1 && str2) {
        *str2++ = 0;
        tonodename = str1;
        tofieldname = str2;

        ok = TRUE;
      }
    }
  }

#if COIN_DEBUG && 0 // debug
  SoDebugError::postInfo("SoBase::readRoute",
                         "%s.%s %s %s.%s",
                         fromnodename.getString(),
                         fromfieldname.getString(),
                         toname.getString(),
                         tonodename.getString(),
                         tofieldname.getString());
#endif // debug

  if (!ok) SoReadError::post(in, "Error parsing ROUTE keyword");
  else {
    SoProto * proto = in->getCurrentProto();
    if (proto) {
      proto->addRoute(fromnodename, fromfieldname, tonodename, tofieldname);
    }
    else {
      SoNode * fromnode = SoNode::getByName(fromnodename);
      SoNode * tonode = SoNode::getByName(tonodename);

      if (!fromnode || !tonode) {
        SoReadError::post(in,
                          "Unable to create ROUTE from %s.%s to %s.%s. "
                          "Delaying.",
                          fromnodename.getString(), fromfieldname.getString(),
                          tonodename.getString(), tofieldname.getString());
        in->addRoute(fromnodename, fromfieldname, tonodename, tofieldname);
      }

      (void)SoBase::connectRoute(in, fromnodename, fromfieldname,
                                 tonodename, tofieldname);
    }
  }
  return ok;
}

//
// private method that sends a notify to auditor based on type
//
void
SoBase::doNotify(SoNotList * l, const void * auditor, const SoNotRec::Type type)
{
  l->setLastType(type);
  switch (type) {
  case SoNotRec::CONTAINER:
  case SoNotRec::PARENT:
    {
      SoFieldContainer * obj = (SoFieldContainer *)auditor;
      obj->notify(l);
    }
    break;

  case SoNotRec::SENSOR:
    {
      SoDataSensor * obj = (SoDataSensor *)auditor;
#if COIN_DEBUG && 0 // debug
      SoDebugError::postInfo("SoAuditorList::notify",
                             "notify and schedule sensor: %p", obj);
#endif // debug
      // don't schedule the sensor here. The sensor instance will do
      // that in notify() (it might also choose _not_ to schedule),
      obj->notify(l);
    }
    break;

  case SoNotRec::FIELD:
  case SoNotRec::ENGINE:
    {
      // We used to check whether or not the fields was already
      // dirty before we transmitted the notification
      // message. This is _not_ correct (the dirty flag is
      // conceptually only relevant for whether or not to do
      // re-evaluation), so don't try to "optimize" the
      // notification mechanism by re-introducing that "feature".
      // :^/
      ((SoField *)auditor)->notify(l);
    }
    break;

  default:
    assert(0 && "Unknown auditor type");
  }
}

/*!
  \internal
  \since Coin 2.3
*/
void
SoBase::staticDataLock(void)
{
  CC_MUTEX_LOCK(SoBase::PImpl::global_mutex);
}

/*!
  \internal
  \since Coin 2.3
*/
void
SoBase::staticDataUnlock(void)
{
  CC_MUTEX_UNLOCK(SoBase::PImpl::global_mutex);
}

/*!
  \internal
*/
SoNotRec
SoBase::createNotRec(void)
{
  return SoNotRec(this);
}

#undef ALIVE_PATTERN

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

#ifdef COIN_TEST_SUITE

/*This test targets the implementation of SoWriterefCounter::getWriteName
  in the source file SoWriterefCounter.cpp. Test is put here because the
  SoWriterefCounter class is not part of the public API. It is being called
  from here 
  */

#include <Inventor/SoDB.h>
#include <Inventor/SoOutput.h>
#include <Inventor/actions/SoWriteAction.h>
#include <Inventor/nodes/SoSeparator.h>
#include <Inventor/actions/SoToVRML2Action.h>
#include <Inventor/VRMLnodes/SoVRMLGroup.h>

 static char * buffer;
  static size_t buffer_size = 0;

//
// If function is copied from SoWriterefCounter.cpp as pricate classes cannot be called from the test suite
//
  static SbBool
dont_mangle_output_names(const SoBase *base)
{
  static int COIN_DONT_MANGLE_OUTPUT_NAMES = -1;

  // Always unmangle node names in VRML1 and VRML2
  if (base->isOfType(SoNode::getClassTypeId()) &&
      (((SoNode *)base)->getNodeType()==SoNode::VRML1 ||
     ((SoNode *)base)->getNodeType()==SoNode::VRML2)) return TRUE;

  if (COIN_DONT_MANGLE_OUTPUT_NAMES < 0) {
    COIN_DONT_MANGLE_OUTPUT_NAMES = 0;
    const char * env = coin_getenv("COIN_DONT_MANGLE_OUTPUT_NAMES");
    if (env) COIN_DONT_MANGLE_OUTPUT_NAMES = atoi(env);
  }
  return COIN_DONT_MANGLE_OUTPUT_NAMES ? TRUE : FALSE;
}

  static void *
  buffer_realloc(void * bufptr, size_t size)
  {
    buffer = (char *)realloc(bufptr, size);
    buffer_size = size;
    return buffer;
  }


BOOST_AUTO_TEST_CASE(checkWriteWithMultiref)
{
	SoDB::init();
	   SoNode* scenegraph;
       SoSeparator *root = new SoSeparator;
       root->ref();
       root->setName("root");
		scenegraph = root;
       SoSeparator *n0 = new SoSeparator;
       SoSeparator *a0 = new SoSeparator;
       SoSeparator *a1 = new SoSeparator;
       SoSeparator *a2 = new SoSeparator;
       SoSeparator *a3 = new SoSeparator;
       SoSeparator *b0 = new SoSeparator;
       SoSeparator *b1 = new SoSeparator;
       SoSeparator *b2 = new SoSeparator;
       SoSeparator *b3 = new SoSeparator;
       SoSeparator *b4 = new SoSeparator;
       SoSeparator *c0 = new SoSeparator;

       a2->setName(SbName("MyName"));
       b0->setName(SbName("MyName"));
       b1->setName(SbName("MyName"));
       b2->setName(SbName("MyName"));
       b4->setName(SbName("MyName"));
       c0->setName(SbName("MyName"));

       root->addChild(n0);
       root->addChild(n0);
       root->addChild(a0);
       a0->addChild(b0);
       a0->addChild(b1);
       root->addChild(b0);
       root->addChild(a1);
       a1->addChild(b2);
       a1->addChild(b1);
       root->addChild(b1);
       root->addChild(a2);
       root->addChild(a2);
       root->addChild(a3);
       a3->addChild(b3);
       b3->addChild(c0);
       b3->addChild(c0);
       a3->addChild(b4);
       a3->addChild(a2);



/*
       Correct output file if dont_mangle_names:

       #VRML V1.0 ascii

       DEF root Separator {
         DEF +0 Separator {
         }
         USE +0
         Separator {
           DEF MyName Separator {
           }
           DEF MyName+1 Separator {
           }
         }
         USE MyName
         Separator {
           DEF MyName Separator {
           }
           USE MyName+1
         }
         USE MyName+1
         DEF MyName Separator {
         }
         USE MyName
         Separator {
           Separator {
             DEF MyName+2 Separator {
             }
             USE MyName+2
           }
           DEF MyName+3 Separator {
           }
           USE MyName
         }
       }
    */

	   /* correct outputfile for default OIV behavoir:
	   #VRML V1.0 ascii


DEF root Separator {

  DEF +0 Separator {

  }
  USE +0
  Separator {

    DEF MyName Separator {

    }
    DEF MyName+1 Separator {

    }
  }
  USE MyName
  Separator {

    DEF MyName+2 Separator {

    }
    USE MyName+1
  }
  USE MyName+1
  DEF MyName+3 Separator {

  }
  USE MyName+3
  Separator {

    Separator {

      DEF MyName+4 Separator {

      }
      USE MyName+4
    }
    DEF MyName+5 Separator {

    }
    USE MyName+3
  }
}
*/
	    SoVRMLGroup *newroot;
	   for(int j=0;j<2;j++) {
		   if(j==1) {
	SoToVRML2Action tovrml2;
      tovrml2.apply(root);
      newroot = tovrml2.getVRML2SceneGraph();
	  newroot->ref();
	  scenegraph = newroot;
		   }


	   buffer = (char*)malloc(1024);
       SoOutput out;
       // out.openFile("out.wrl"); 
	   out.setBuffer(buffer, 1024,buffer_realloc);
       out.setHeaderString(SbString("#VRML V1.0 ascii"));
       SoWriteAction wra(&out);
       wra.apply(scenegraph);
	   SbString s(buffer);
	   free(buffer);

	   int pos;
	   SbString ss;

	   SbList<SbString> node_names(15);
	   if(j==1)
		BOOST_CHECK_MESSAGE(dont_mangle_output_names(scenegraph)==TRUE,"don't mangel should be TRUE");
	   else
		BOOST_CHECK_MESSAGE(dont_mangle_output_names(scenegraph)==FALSE,"don't mangle should be FALSE");

	   if(dont_mangle_output_names(scenegraph)) {
		   node_names.append("_+0");
		   node_names.append("_+0");
		   node_names.append("MyName");
		   node_names.append("MyName+1");
		   node_names.append("MyName");
		   node_names.append("MyName");
		   node_names.append("MyName+1");
		   node_names.append("MyName+1");
		   node_names.append("MyName");
		   node_names.append("MyName");
		   node_names.append("MyName+2");
		   node_names.append("MyName+2");
		   node_names.append("MyName+3");
		   node_names.append("MyName");
	   }
	   else {
		   node_names.append("_+0");
		   node_names.append("_+0");
		   node_names.append("MyName");
		   node_names.append("MyName+1");
		   node_names.append("MyName");
		   node_names.append("MyName+2");
		   node_names.append("MyName+1");
		   node_names.append("MyName+1");
		   node_names.append("MyName+3");
		   node_names.append("MyName+3");
		   node_names.append("MyName+4");
		   node_names.append("MyName+4");
		   node_names.append("MyName+5");
		   node_names.append("MyName+3");
	   }
   
	   int list_index = 0;
	   SbBool fail = false;
	   ss = s;
	   for(int i=0;i<node_names.getLength();i++) {
		   pos = ss.find(node_names[i]);
		   if(pos==-1) {
			   fail = true;
			   break;
		   }
		   ss = ss.getSubString(pos+node_names[i].getLength(),ss.getLength());
	   }


	   BOOST_CHECK_MESSAGE(!fail,"Check failed, written node names should match test template");
	   
	   }
	   
	
       root->unref();
	   newroot->unref();
 }

#endif // COIN_TEST_SUITE

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