5.12. Creating a New Element

This example creates an element called TemperatureElement that holds the current temperature of shapes during traversal. This element is derived from the SoFloatElement SoFloatElement SoFloatElement class.

Example 5-1 shows the header file for the TemperatureElement.

Example 5.1.  TemperatureElement.h

#include <Inventor/elements/SoFloatElement.h>

class TemperatureElement : public SoFloatElement {

   SO_ELEMENT_HEADER(TemperatureElement);

 public:
   // Initializes the TemperatureElement class
   static void    initClass();

   // Initializes element
   virtual void   init(SoState *state);

   // Sets the current temperature in the state to the given
   // temperature (in degrees Fahrenheit)
   static void    set(SoState *state, SoNode *node, float temp);

   // Returns the current temperature from the state
   static float   get(SoState *state);

   // Returns the default temperature
   static float   getDefault()         { return 98.6; }

 private:
   virtual ~TemperatureElement();
};


Example 5-2 shows the source code for the TemperatureElement.

Example 5.2.  TemperatureElement.c++

#include "TemperatureElement.h"

SO_ELEMENT_SOURCE(TemperatureElement);

// Initializes the TemperatureElement class.

void
TemperatureElement::initClass()
{
   SO_ELEMENT_INIT_CLASS(TemperatureElement, SoFloatElement);
}

// Destructor

TemperatureElement::~TemperatureElement()
{
}

// Initializes the first instance used in an action's state.

void
TemperatureElement::init(SoState *)
{
   data = getDefault();
}

// Sets the current temperature in the state.

void
TemperatureElement::set(SoState *state, SoNode *node,
                  float temp)
{
   // Use the corresponding method on SoFloatElement to set the
   // value in the top instance in the state
   SoFloatElement::set(classStackIndex, state, node, temp);
}

// Returns the current temperature from the state.

float
TemperatureElement::get(SoState *state)
{
   // Use the corresponding method on SoFloatElement to get the
   // value from the top instance in the state
   return SoFloatElement::get(classStackIndex, state);
}