/**************************************************************************\
 *
 *  This file is part of the Coin 3D visualization library.
 *  Copyright (C) 1998-2006 by Systems in Motion.  All rights reserved.
 *
 *  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 Systems in Motion about acquiring
 *  a Coin Professional Edition License.
 *
 *  See http://www.coin3d.org/ for more information.
 *
 *  Systems in Motion, Postboks 1283, Pirsenteret, 7462 Trondheim, 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 <assert.h>
#include <string.h>

#include <Inventor/fields/SoFields.h>

#ifdef CVE_ENABLED
#define _WIN32_WINNT 0x0400 // threadsutilp.h leads to include winsock.h instead of winsock2.h
                            // that finishes at fail on TNet.c compilation
#endif
#include <Inventor/C/threads/threadsutilp.h>
#include <Inventor/C/tidbitsp.h>
#include <Inventor/SoDB.h>
#include <Inventor/SoInput.h>
#include <Inventor/SoOutput.h>
#include <Inventor/actions/SoWriteAction.h>
#include <Inventor/engines/SoConvertAll.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/SbHash.h>
#include <Inventor/misc/SoProtoInstance.h>
#include <Inventor/nodes/SoNode.h>
#include <Inventor/sensors/SoDataSensor.h>
#include "../io/SoWriterefCounter.h"
#include <coindefs.h> // COIN_STUB()

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

#ifdef COIN_THREADSAFE
#include <Inventor/C/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;

// 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), 
#ifdef CVE_ENABLED
    cveStorage(NULL),
#endif
    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);

#ifdef CVE_ENABLED
    assert(cveStorage == NULL);
#endif
  }
#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;

#ifdef CVE_ENABLED
  SoCveStorage *cveStorage;
#endif

  // 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 (((void*)(o->getNodeContainer())) == this->lastnotify) return i;
      }
      else {
        if (((void*)(o->getContainer())) == this->lastnotify) return i;
      }
    }
    return -1;
  }
  int findFanInField(void) const {
    for (int i = 0; i < this->masterfields.getLength(); i++) {
      if (((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;

};


#ifdef CVE_ENABLED

// Modified files in Coin:
// SoField.h SoField.cpp
// SoSubField.h


// needed by other fields;
// To avoid modifications in
// SoSFEnum.cpp SoSFPath.cpp SoSFNode.cpp SoSFEngine.cpp,
// we are doing it here.
#include <Inventor/fields/SoSFEnum.h>
#include <Inventor/fields/SoMFEnum.h>
#include <Inventor/fields/SoSFNode.h>
#include <Inventor/fields/SoMFNode.h>
#include <Inventor/fields/SoSFPath.h>
#include <Inventor/fields/SoSFEngine.h>
CVE_SFIELD_VALUE_SOURCE(SoSFEnum, int, int);
CVE_MFIELD_VALUE_SOURCE(SoMFEnum, int, int);
CVE_SFIELD_VALUE_SOURCE(SoSFNode, SoNode *, SoNode *);
CVE_MFIELD_VALUE_SOURCE(SoMFNode, SoNode *, SoNode *);
CVE_SFIELD_VALUE_SOURCE(SoSFPath, SoPath *, SoPath *);
CVE_MFIELD_VALUE_SOURCE(SoMFPath, SoPath *, SoPath *);
CVE_SFIELD_VALUE_SOURCE(SoSFEngine, SoEngine *, SoEngine *);
CVE_MFIELD_VALUE_SOURCE(SoMFEngine, SoEngine *, SoEngine *);


// compilation of CVE files

// these two files need to be compiled first
#include "../cve/SbNetBasic.cpp"
#if defined(__WIN32__) || defined(_WIN32) // there are errno redefine warnings on Windows
# undef errno
# include "../cve/TNet.c"
# undef errno // errno macro value should be restored here if necessary
# ifdef THIS // winsock2.h pollutes namespace with THIS
#  undef THIS
# endif
#else
# include "../cve/TNet.c"
#endif

#include "../cve/SoComputer.cpp"
#include "../cve/SoDistributionGroup.cpp"
#include "../cve/SbNetListener.cpp"
#include "../cve/SoNetwork.cpp"
#include "../cve/SoNetworkP.cpp"
#include "../cve/SbRefObject.cpp"
#include "../cve/SbTimeStamp.cpp"
#include "../cve/SbTransaction.cpp"
#include "../cve/SbTransactionP.cpp"
#include "../cve/SbSceneAssert.cpp"
#include "../cve/SoMFComputer.cpp"
#include "../cve/SoMFNetListener.cpp"
#include "../cve/SbNetMessage.cpp"

// linking with winsock library
#if defined(__WIN32__) || defined(_WIN32)
#pragma comment (lib, "wsock32.lib")
#endif



void SoField::extendCveStorageIfNecessary()
{
  extendStorageIfNecessary();
  if (storage->cveStorage == NULL)
    storage->cveStorage = new SoCveStorage;
}

// called from SoField destructor and SoDistributionGroup::removeFromDict(SoField*)
void SoField::releaseCveStorage()
{
  SoCveStorage *cveStorage = getCveStorage();
  if (cveStorage) {
    if (cveStorage->connectionId != 0) {
      cveStorage->dg->removeFromDict(this); // SoDistributionGroup::removeFromDict calls SoField::releaseCveStorage()
                                            // again but with cveStorage->connectionId set to zero.
      return;
    }
    delete cveStorage;
    storage->cveStorage = NULL;
  }
}

struct SoCveStorage* SoField::getCveStorage()
{
  if (!hasExtendedStorage()) return NULL;
  return storage->cveStorage;
}

const struct SoCveStorage* SoField::getCveStorage() const
{
  if (!hasExtendedStorage()) return NULL;
  return storage->cveStorage;
}

void SoField::transactionNotifyRead(int index, class SbTransaction *t,
                                    SoFieldContainer *root, const class SbIntList &path,
                                    SbBool predictedOnly)
{
  assert(t && "Passing NULL pointer.");

  if (t->getState() != SbTransaction::CONSTRUCTING) {
    assert(0 && "It is not possible to change read set of transaction that is not in CONSTRUCTING state.");
    return;
  }

  // get cve storage
  extendCveStorageIfNecessary();
  SoCveStorage *cveStorage = getCveStorage();

  // create SbReadSetItem
  SbReadSetItem *item = new SbReadSetItem;
  item->field = this;
  item->transaction = t;

  item->itemId.set(t, root, path, this);

  // check connectionId validity
  if (item->itemId.connectionId == -1) {
    static SbBool errorReported = FALSE;
    if (!errorReported) {
      errorReported = TRUE;
      SoDebugError::post("SoField::transactionNotifyRead",
                         "transactionNotifyRead can not determine connectionId.\n"
                         "This can be caused by: calling function for a field without connection"
                         "or if root is non-NULL, root must have connection."
                         "Ignoring transactionNotifyRead() call.\n"
                         "This error is reported only once.");
    }
    delete item;
    return;
  }

  // get readSetItem timestamp
  int c = getCveNumValues(predictedOnly);
  assert(index < c && "Invalid index.");
  assert(index >= 0 || index == LATEST || index == COMMITTED && "Invalid index.");
  SbWriteSetItem *wsi = getCveWriteItem(index, predictedOnly); // wsi always exists
  assert(wsi && "WriteItem not found.");
  SbTransaction *wt = wsi->getTransaction(); // wt does not exist when returning commited value
  if (wt) {
    item->timeStamp = wt->getTimeStamp();
    item->flags.commitPredictor = wt->getCommitPredictor();
  } else {
    item->timeStamp = cveStorage->commitTime; // if there was no commit, getCveWriteItem created fake one
    item->flags.commitPredictor = TRUE;
  }
  item->flags.writeArrived = TRUE;

  // check wheter the field is already in the read set
  // - when one field is tried to append multiple times with different paths, it is appended only once
  // - appending item must have the same timeStamp
  int i;
  c = cveStorage->unscheduledReads.getLength();
  for (i=0; i<c; i++) {
    SbReadSetItem *ri = cveStorage->unscheduledReads[i];
    if (ri->transaction == t) {
      if (ri->timeStamp != item->timeStamp) {
        static SbBool errorReported = FALSE;
        if (!errorReported) {
          errorReported = TRUE;
          SoDebugError::post("SoField::transactionNotifyRead",
                             "It is forbidden to append the same field with different timestamps\n"
                             "to the read set multiple times. The append is ignored.\n"
                             "This error is reported only once.");
        }
        delete item;
        return;
      }
    }
  }

  // append writeSetItem to the lists
  cveStorage->unscheduledReads.append(item);
  t->appendReadSetItem(item);
}

const SbTimeStamp& SoField::getCveTimeStamp(int index, SbBool predictedOnly) const
{
  if (index < 0) {
    switch (index) {
    case SoField::LATEST:
    case SoField::COMMITTED: {
      SbWriteSetItem *wsi = getCveWriteItem(index, predictedOnly);
      assert(wsi);
      SbTransaction *t = wsi->getTransaction();
      if (t != NULL)
        return t->getTimeStamp();
      else {
        // this will happen for commited values
        const SoCveStorage *cveStorage = getCveStorage();
        assert(wsi == cveStorage->committedValue);
        return cveStorage->commitTime;
      }
    }
    case SoField::USER_VIEW:
    default:
      assert(0 && "Wrong index value. getCveTimeStamp called with USER_VIEW index value.");
      return SbTimeStamp::zero();
    }
  } else {

    SbWriteSetItem *wsi = getCveWriteItem(index, predictedOnly);
    if (wsi == NULL)
      return SbTimeStamp::zero();

    return wsi->getTransaction()->getTimeStamp();
  }
}

SbWriteSetItem* SoField::getCveWriteItem(int index, SbBool predictedOnly) const
{
  if (index < 0) {
    switch (index) {
    case SoField::LATEST: {
      int n = getCveNumValues(predictedOnly); \
      if (n > 0)  return getCveWriteItem(n-1, predictedOnly);
      else; // return COMMITED value
    }
    case SoField::COMMITTED: {
      // Return commited data item.
      // If no commited value is present, then allocate it 
      // with current field value and zero timeStamp without identity.
      SoField *THIS = (SoField*)this;
      THIS->extendCveStorageIfNecessary();
      SoCveStorage *cveStorage = THIS->getCveStorage();

      // create one if it does not exist
      if (cveStorage->committedValue == NULL) {
        cveStorage->committedValue = cveCreateWriteSetItem();
        cveGetFieldValue(cveStorage->committedValue);
        cveStorage->committedValue->makeCommitted(); // this will set transaction to NULL
        cveStorage->commitTime = SbTimeStamp::zero(); // there is no commit time in this case => set it to zero
      }

      return cveStorage->committedValue;
    }
    default:
      assert(0 && "Wrong index value.");
      return NULL;
    }
  } else {
    const SoCveStorage *cveStorage = getCveStorage();

    /* check whether cveStorage is allocated */ \
    if (cveStorage == NULL) {
      assert(0 && "getCveWriteItem() index out of bounds (no cveStorage allocated). "
                  "Use getCveNumValues() to get number of speculative values.");
      return NULL;
    }

    /* check index bounds */
    if (index >= getCveNumValues(predictedOnly)) {
      assert(0 && "Index is out of bounds. "
                  "Use getCveNumValues() to get number of speculative values.");
      return NULL;
    }

    if (!predictedOnly)

      /* return value */
      return cveStorage->writeList[index];
    else {

      /* calculate index */
      int i = -1;
      int j = -1;
      do {
        i++;
        if (cveStorage->writeList[i]->getTransaction()->getCommitPredictor())  j++;
      } while (j != index);

      /* return value */
      return cveStorage->writeList[i];
    }
  }
}


void SoField::setCommitTimeStamp(const SbTimeStamp& ts)
{
  extendCveStorageIfNecessary();
  SoCveStorage *cveStorage = getCveStorage();
  assert(cveStorage);
  cveStorage->commitTime = ts;
}


int SoField::getCveNumValues(SbBool predictedOnly) const
{
  return getNumTransactions(predictedOnly);
}


SbBool SoField::cveIsPredicted(int index) const
{
  if (index < 0) {
    if (index != SoField::LATEST) {
      assert(0 && "Wrong index value. cveIsPredicted called with invalid index value.");
      return FALSE;
    }
  }

  SbWriteSetItem *wsi = getCveWriteItem(index, FALSE);
  assert(wsi);

  SbTransaction *t = wsi->getTransaction();
  if (t != NULL)
    return t->getCommitPredictor();
  else {
    // this will happen for commited and starting values (index==LATEST)
    assert(index == SoField::LATEST);
    return TRUE;
  }
}


SbTransaction* SoField::getTransaction(int index, SbBool predictedOnly) const
{
  if (index < 0) {
    switch (index) {
    case SoField::LATEST: {
      int n = getNumTransactions(predictedOnly);
      if (n > 0)  return getTransaction(n-1, predictedOnly);
      return NULL;
    }
    default:
      assert(0 && "Wrong index value. getTransaction called with invalid index value.");
      return NULL;
    }
  } else {

    SbWriteSetItem *wsi = getCveWriteItem(index, predictedOnly);
    if (wsi == NULL)
      return NULL;

    return wsi->getTransaction();
  }
}


int SoField::getNumTransactions(SbBool predictedOnly) const
{
  const SoCveStorage *cveStorage = getCveStorage();
  if (cveStorage) {
    if (!predictedOnly)  
      return cveStorage->writeList.getLength();
    else {
      int i, c = cveStorage->writeList.getLength();
      int num = 0;
      for (i=0; i<c; i++)
        if (cveStorage->writeList[i]->getTransaction()->getCommitPredictor())  num++;
      return num;
    }
  } else
    return 0;
}

#endif // CVE_ENABLED




// 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 (((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);

private:
  static void hashExitCleanup(void);
  static SbHash<char **, char *> * ptrhash;
};

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

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

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

void *
SoFieldP::hashRealloc(void * bufptr, size_t size)
{
  char ** bufptrptr = NULL;
  int ok = SoFieldP::ptrhash->get((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 = (char*) malloc(size);
    memcpy(newbuf, bufptr, SOFIELD_GET_STACKBUFFER_SIZE);
  }
  else {
    newbuf = (char *)realloc(bufptr, size);
  }
  if (newbuf != bufptr) {
    ok = SoFieldP::ptrhash->remove((char *)bufptr);
    assert(ok);
    *bufptrptr = newbuf;
    SoFieldP::ptrhash->put(newbuf, bufptrptr);
  }

  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();

#ifdef CVE_ENABLED
  releaseCveStorage();
#endif

  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:
        ((SoEngineOutput *)obj)->removeConnection(this);
        break;

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

      case SoNotRec::SENSOR:
        ((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);
}

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

// atexit
static 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((coin_atexit_f*) field_mutex_cleanup, CC_ATEXIT_NORMAL);

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

/*!
  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)
{
  // 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("");
      if (fcname != SbName("")) {
        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);
  }
}

/*!
  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 = (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((void *)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.

  if (sofield_mutex) {
    CC_MUTEX_LOCK(sofield_mutex); // need to lock since a static array is used
  }

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

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

  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 = ((char *)buffer) + offset;

  // dealloc tmp memory buffer
  if (bufferptr) { free(bufferptr); }
  ok = SoFieldP::getReallocHash()->remove(bufferptr ? bufferptr : initbuffer);
  assert(ok);

  if (sofield_mutex) {
    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 = (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 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 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 ? 
      (SoFieldContainer*) eout->getContainer() : 
      (SoFieldContainer*) eout->getNodeContainer();    
    if (SoFieldContainer::checkCopy(fc)) return TRUE;
    if (isengine || (fc->isOfType(SoEngine::getClassTypeId()) &&
                     ((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 = (SoNodeEngine*) 
        masterengine->copyThroughConnection(); 
      copyeo = copyengine->getOutput(name); 
    }
    else {
      SbName name;
      SoEngine * masterengine = master->getContainer();
      (void) masterengine->getOutputName(master, name);
      SoEngine * copyengine = (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 {
      in->putBack(c);

      // First check if there's a field-to-field connection here as
      // the default value following the field can be omitted.
      if (in->read(c)) { // if-check in case EOF on an SoField::set() invocation
        // 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 (c == CONNECTIONCHAR) { 
          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

  SbBool vrml2connection = FALSE;

  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((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((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 <stdio.h>

/*!
  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 = (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 = (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 = (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()) ?
      ((SoEngine*)fc)->getOutput(mastername) : NULL;

    if (!masteroutput) {
      masteroutput =
        fc->isOfType(SoNodeEngine::getClassTypeId()) ?
        ((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((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() ?
      ((SoNodeEngine *)fc)->getOutputName(enginemaster, mastername) :
      ((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 = (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((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();
  SoSFBox3s::initClass();
#ifdef COIN_NEXT_MINOR
  SoSFBox3f::initClass();
#endif
  SoSFBool::initClass();
  SoSFColor::initClass();
  SoSFEngine::initClass();
  SoSFFloat::initClass();
  SoSFShort::initClass();
  SoSFUShort::initClass();
  SoSFInt32::initClass();
  SoSFUInt32::initClass();
  SoSFVec2f::initClass();
  SoSFVec2s::initClass();
  SoSFVec3d::initClass();
  SoSFVec3f::initClass();
  SoSFVec3s::initClass();
  SoSFVec4f::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();
  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();
  SoMFVec2f::initClass();
  SoMFVec3d::initClass();
  SoMFVec3f::initClass();
  SoMFVec4f::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.

  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
