Hi Sebastian,

On 1/07/10 19:15 , Sebastian Messerschmidt wrote:
>>> Thank you anyways for giving me an appropriate pointer the UserData class. 
>>> I'll will dig
>>> deeper into it.
>>> Comments from other people are welcome.
>>
>> I was doing some work on something similar a while ago to associating 
>> loader-specific data
>> with the loaded object (in my case meta-data with an osg::Image).  Alas, the 
>> requirement
>> is currently on the back-burner so I haven't pursued this further.
>>
>> My approach was to add a ref_ptr<PropertyMap> to osg::Object.
>> PropertyMap is a map of strings to ref_ptr objects.
>> A templated helper class 'Property' allows type-safe storage of data in this 
>> map.
>>
>> Both osg::Object userdata and osg::Node descriptions are stored using this 
>> scheme.
>> The memory footprint for osg::Object stays the same ('ref_ptr<Referenced> 
>> _userData' is
>> replaced with 'ref_ptr<PropertyMap> _properties') and the footprint for 
>> osg::Node is
>> reduced by losing std::vector<string>.
>>
>> API backwards compatibility is maintained through appropriate 
>> getters/setters.
> 
> Okay, that sounds very interesting. I wasn't aware of the fact that there 
> already is a
> userData facility. Your approach seems to be exactly what I could use here. 
> The problem
> however is, that a higher level concept is needed to describe the data the 
> loaders should
> extract.

That is indeed slighty different, as I didn't worry about this bit.  For me the 
loader
would simply but everything it thinks interesting into properties.

>> The code is still compiling but isn't terribly well exercised or tested.  I 
>> can post a
>> copy if you're interested.
> 
> That would be nice, I guess the only change is inside osg::Object while the 
> additional
> classes for Property and PropertyMap reside in different files. You can send 
> it directly
> to me at the email-adress above.
> If this is working for me you can be assured that I will undergo heavy 
> testing as I need
> this as a primary feature.

I've attached a modified osg/Object, osg/Node and new osg/Property as well as a 
simple
test case, I hope this covers everything.

Cheers,
/ulrich
/*
 * Properties test
 *
 * COMPILE: g++ -O -o props props.cpp -L/usr/local/lib -losgDB -losg 
-lOpenThreads
 */

#include <iostream>
#include <cmath>
#include <assert.h>

#include <osg/io_utils>

#include <osg/Node>
#include <osg/Image>


using namespace std;


namespace
{
    const char* FOO = "sandbox.foo";
    const char* BAR = "sandbox.bar";
    const char* BAZ = "sandbox.baz";
    const char* MYDATA = "sandbox.mydata";


    struct MyData : public osg::Referenced
    {
        MyData() : osg::Referenced(), frameRate(25.0f), timeCode("00:00:00:00") 
{}

        float frameRate;
        std::string timeCode;

    private:
        ~MyData() {}
    };


    void testObject(osg::Object* obj)
    {
        cout << "*** testObject " << obj << " " << obj->className() << endl;

        // int
        obj->setProperty<int>(FOO, 23);
        int foo;
        assert(obj->tryGetProperty(FOO, foo) == true);
        assert(foo = 23);
        printf("int okay\n");

        // float
        obj->setProperty<float>(BAR, 42.0f);
        float bar;
        assert(obj->tryGetProperty(BAR, bar) == true);
        assert(bar = 42.0f);
        printf("float okay\n");

        // string
        obj->setProperty<std::string>(BAZ, "BAZ");
        std::string baz;
        assert(obj->tryGetProperty(BAZ, baz) == true);
        assert(baz == "BAZ");
        printf("string okay\n");

        // clear
        obj->clearProperty(FOO);
        assert(obj->tryGetProperty(FOO, foo) == false);
        printf("clear okay\n");

        // type safety
        assert(obj->tryGetProperty<int>(BAR, foo) == false);
        printf("type safety okay\n");

        {
            // osg::Reference derived
            MyData* myData = new MyData;
            myData->frameRate = 23.0f;
            myData->timeCode = "00:00:42:00";

            // NOTE: must be cast to Referenced or the specialisation doesn't 
work :-(
            obj->setProperty(MYDATA, (osg::Referenced*) myData);

            osg::Referenced* ref = obj->getProperty(MYDATA);
            assert(ref != NULL);

            MyData* myData1 = dynamic_cast<MyData*>(ref);
            assert(myData1 == myData);
            assert(myData1->frameRate == 23.0f);
            assert(myData1->timeCode == "00:00:42:00");

            printf("derived okay\n");
            // no need to delete myData, is ref-counted inside the properties
        }

        {
            // userdata
            MyData* myData = new MyData;
            myData->frameRate = 42.0f;
            obj->setUserData(myData);

            osg::Referenced* ref = obj->getUserData();
            assert(ref == myData);

            MyData* myData1 = dynamic_cast<MyData*>(ref);
            assert(myData1 == myData);
            assert(myData1->frameRate == 42.0f);

            printf("userdata okay\n");
            // no need to delete myData, is ref-counted inside the properties
        }
    }

    void testNode(osg::Node* node)
    {
        cout << "*** testNode " << node << " " << node->className() << endl;

        // Descriptions backwards compatibility
        const osg::Node::DescriptionList& cdesc = node->getDescriptions();
        assert(cdesc.size() == 0);

        node->getDescriptions().push_back("foobar");
        node->getDescriptions().push_back("baz");
        assert(node->getDescriptions().size() == 2);

        assert(node->getDescriptions()[0] == "foobar");
        assert(node->getDescriptions()[1] == "baz");

        printf("description okay\n");

        testObject(node);
    }
}


int main(int argc, char** argv)
{
    osg::ref_ptr<osg::Image> img(new osg::Image);
    testObject(img.get());

    osg::ref_ptr<osg::Node> node(new osg::Node);
    testNode(node.get());

    return 0;
}
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
 *
 * This library is open source and may be redistributed and/or modified under  
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 * OpenSceneGraph Public License for more details.
 */


#ifndef OSG_NODE
#define OSG_NODE 1

#include <osg/Object>
#include <osg/StateSet>
#include <osg/BoundingSphere>
#include <osg/NodeCallback>

#include <string>
#include <vector>

namespace osg {

class NodeVisitor;
class Group;
class Transform;
class Node;
class Switch;
class Geode;

/** A vector of Nodes pointers which is used to describe the path from a root 
node to a descendant.*/
typedef std::vector< Node* > NodePath;

/** A vector of NodePath, typically used to describe all the paths from a node 
to the potential root nodes it has.*/
typedef std::vector< NodePath > NodePathList;

/** A vector of NodePath, typically used to describe all the paths from a node 
to the potential root nodes it has.*/
typedef std::vector< Matrix > MatrixList;

/** META_Node macro define the standard clone, isSameKindAs, className
  * and accept methods.  Use when subclassing from Node to make it
  * more convenient to define the required pure virtual methods.*/
#define META_Node(library,name) \
        virtual osg::Object* cloneType() const { return new name (); } \
        virtual osg::Object* clone(const osg::CopyOp& copyop) const { return 
new name (*this,copyop); } \
        virtual bool isSameKindAs(const osg::Object* obj) const { return 
dynamic_cast<const name *>(obj)!=NULL; } \
        virtual const char* className() const { return #name; } \
        virtual const char* libraryName() const { return #library; } \
        virtual void accept(osg::NodeVisitor& nv) { if 
(nv.validNodeMask(*this)) { nv.pushOntoNodePath(this); nv.apply(*this); 
nv.popFromNodePath(); } } \
        

/** Base class for all internal nodes in the scene graph.
    Provides interface for most common node operations (Composite Pattern).
*/
class OSG_EXPORT Node : public Object
{
    public:

        /** Construct a node.
            Initialize the parent list to empty, node name to "" and 
            bounding sphere dirty flag to true.*/
        Node();

        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
        Node(const Node&,const CopyOp& copyop=CopyOp::SHALLOW_COPY);

        /** clone an object of the same type as the node.*/
        virtual Object* cloneType() const { return new Node(); }

        /** return a clone of a node, with Object* return type.*/
        virtual Object* clone(const CopyOp& copyop) const { return new 
Node(*this,copyop); }

        /** return true if this and obj are of the same kind of object.*/
        virtual bool isSameKindAs(const Object* obj) const { return 
dynamic_cast<const Node*>(obj)!=NULL; }

        /** return the name of the node's library.*/
        virtual const char* libraryName() const { return "osg"; }

        /** return the name of the node's class type.*/
        virtual const char* className() const { return "Node"; }

        /** convert 'this' into a Group pointer if Node is a Group, otherwise 
return 0.
          * Equivalent to dynamic_cast<Group*>(this).*/
        virtual Group* asGroup() { return 0; }

        /** convert 'const this' into a const Group pointer if Node is a Group, 
otherwise return 0.
          * Equivalent to dynamic_cast<const Group*>(this).*/
        virtual const Group* asGroup() const { return 0; }

        /** Convert 'this' into a Transform pointer if Node is a Transform, 
otherwise return 0.
          * Equivalent to dynamic_cast<Transform*>(this).*/
        virtual Transform* asTransform() { return 0; }

        /** convert 'const this' into a const Transform pointer if Node is a 
Transform, otherwise return 0.
          * Equivalent to dynamic_cast<const Transform*>(this).*/
        virtual const Transform* asTransform() const { return 0; }

        /** Convert 'this' into a Switch pointer if Node is a Switch, otherwise 
return 0.
          * Equivalent to dynamic_cast<Switch*>(this).*/
        virtual Switch* asSwitch() { return 0; }

        /** convert 'const this' into a const Switch pointer if Node is a 
Switch, otherwise return 0.
          * Equivalent to dynamic_cast<const Switch*>(this).*/
        virtual const Switch* asSwitch() const { return 0; }

        /** Convert 'this' into a Geode pointer if Node is a Geode, otherwise 
return 0.
          * Equivalent to dynamic_cast<Geode*>(this).*/
        virtual Geode* asGeode() { return 0; }

        /** convert 'const this' into a const Geode pointer if Node is a Geode, 
otherwise return 0.
          * Equivalent to dynamic_cast<const Geode*>(this).*/
        virtual const Geode* asGeode() const { return 0; }

        /** Visitor Pattern : calls the apply method of a NodeVisitor with this 
node's type.*/
        virtual void accept(NodeVisitor& nv);
        /** Traverse upwards : calls parents' accept method with NodeVisitor.*/
        virtual void ascend(NodeVisitor& nv);
        /** Traverse downwards : calls children's accept method with 
NodeVisitor.*/
        virtual void traverse(NodeVisitor& /*nv*/) {}       

        /** A vector of osg::Group pointers which is used to store the 
parent(s) of node.*/
        typedef std::vector<Group*> ParentList;

        /** Get the parent list of node. */
        inline const ParentList& getParents() const { return _parents; }

        /** Get the a copy of parent list of node. A copy is returned to 
          * prevent modification of the parent list.*/
        inline ParentList getParents() { return _parents; }

        inline Group* getParent(unsigned int i)  { return _parents[i]; }

        /**
         * Get a single const parent of node.
         * @param i index of the parent to get.
         * @return the parent i.
         */
        inline const Group* getParent(unsigned int i) const  { return 
_parents[i]; }

        /**
         * Get the number of parents of node.
         * @return the number of parents of this node.
         */
        inline unsigned int getNumParents() const { return static_cast<unsigned 
int>(_parents.size()); }

        /** Get the list of node paths parent paths.
          * The optional Node* haltTraversalAtNode allows the user to prevent 
traversal beyond a specifed node. */
        NodePathList getParentalNodePaths(osg::Node* haltTraversalAtNode=0) 
const;

        /** Get the list of matrices that transform this node from local 
coordinates to world coordinates.
          * The optional Node* haltTraversalAtNode allows the user to prevent 
traversal beyond a specifed node. */
        MatrixList getWorldMatrices(const osg::Node* haltTraversalAtNode=0) 
const;
        

        /** Set update node callback, called during update traversal. */
        void setUpdateCallback(NodeCallback* nc);

        /** Get update node callback, called during update traversal. */
        inline NodeCallback* getUpdateCallback() { return 
_updateCallback.get(); }

        /** Get const update node callback, called during update traversal. */
        inline const NodeCallback* getUpdateCallback() const { return 
_updateCallback.get(); }

        /** Convenience method that sets the update callback of the node if it 
doesn't exist, or nest it into the existing one. */
        inline void addUpdateCallback(NodeCallback* nc) {
            if (nc != NULL) {
                if (_updateCallback.valid()) 
_updateCallback->addNestedCallback(nc);
                else setUpdateCallback(nc);
            }
        }

        /** Convenience method that removes a given callback from a node, even 
if that callback is nested. There is no error return in case the given callback 
is not found. */
        inline void removeUpdateCallback(NodeCallback* nc) {
            if (nc != NULL && _updateCallback.valid()) {
                if (_updateCallback == nc) 
setUpdateCallback(nc->getNestedCallback());        // replace the callback by 
the nested one
                else _updateCallback->removeNestedCallback(nc);
            }
        }

        /** Get the number of Children of this node which require Update 
traversal,
          * since they have an Update Callback attached to them or their 
children.*/
        inline unsigned int getNumChildrenRequiringUpdateTraversal() const { 
return _numChildrenRequiringUpdateTraversal; }


        /** Set event node callback, called during event traversal. */
        void setEventCallback(NodeCallback* nc);

        /** Get event node callback, called during event traversal. */
        inline NodeCallback* getEventCallback() { return _eventCallback.get(); }

        /** Get const event node callback, called during event traversal. */
        inline const NodeCallback* getEventCallback() const { return 
_eventCallback.get(); }

        /** Convenience method that sets the event callback of the node if it 
doesn't exist, or nest it into the existing one. */
        inline void addEventCallback(NodeCallback* nc) {
            if (nc != NULL) {
                if (_eventCallback.valid()) 
_eventCallback->addNestedCallback(nc);
                else setEventCallback(nc);
            }
        }

        /** Convenience method that removes a given callback from a node, even 
if that callback is nested. There is no error return in case the given callback 
is not found. */
        inline void removeEventCallback(NodeCallback* nc) {
            if (nc != NULL && _eventCallback.valid()) {
                if (_eventCallback == nc) 
setEventCallback(nc->getNestedCallback());        // replace the callback by 
the nested one
                else _eventCallback->removeNestedCallback(nc);
            }
        }

        /** Get the number of Children of this node which require Event 
traversal,
          * since they have an Event Callback attached to them or their 
children.*/
        inline unsigned int getNumChildrenRequiringEventTraversal() const { 
return _numChildrenRequiringEventTraversal; }


        /** Set cull node callback, called during cull traversal. */
        void setCullCallback(NodeCallback* nc) { _cullCallback = nc; }

        /** Get cull node callback, called during cull traversal. */
        inline NodeCallback* getCullCallback() { return _cullCallback.get(); }

        /** Get const cull node callback, called during cull traversal. */
        inline const NodeCallback* getCullCallback() const { return 
_cullCallback.get(); }

        /** Convenience method that sets the cull callback of the node if it 
doesn't exist, or nest it into the existing one. */
        inline void addCullCallback(NodeCallback* nc) {
            if (nc != NULL) {
                if (_cullCallback.valid()) _cullCallback->addNestedCallback(nc);
                else setCullCallback(nc);
            }
        }

        /** Convenience method that removes a given callback from a node, even 
if that callback is nested. There is no error return in case the given callback 
is not found. */
        inline void removeCullCallback(NodeCallback* nc) {
            if (nc != NULL && _cullCallback.valid()) {
                if (_cullCallback == nc) 
setCullCallback(nc->getNestedCallback());        // replace the callback by the 
nested one
                else _cullCallback->removeNestedCallback(nc);
            }
        }

        /** Set the view frustum/small feature culling of this node to be 
active or inactive.
          * The default value is true for _cullingActive. Used as a guide
          * to the cull traversal.*/
        void setCullingActive(bool active);

        /** Get the view frustum/small feature _cullingActive flag for this 
node. Used as a guide
          * to the cull traversal.*/
        inline bool getCullingActive() const { return _cullingActive; }

        /** Get the number of Children of this node which have culling 
disabled.*/
        inline unsigned int getNumChildrenWithCullingDisabled() const { return 
_numChildrenWithCullingDisabled; }

        /** Return true if this node can be culled by view frustum, occlusion 
or small feature culling during the cull traversal.
          * Note, returns true only if no children have culling disabled, and 
the local _cullingActive flag is true.*/
        inline bool isCullingActive() const { return 
_numChildrenWithCullingDisabled==0 && _cullingActive && getBound().valid(); }

        /** Get the number of Children of this node which are or have 
OccluderNode's.*/
        inline unsigned int getNumChildrenWithOccluderNodes() const { return 
_numChildrenWithOccluderNodes; }

        
        /** return true if this node is an OccluderNode or the subgraph below 
this node are OccluderNodes.*/
        bool containsOccluderNodes() const;


        /**
        * This is a set of bits (flags) that represent the Node.
        * The default value is 0xffffffff (all bits set).
        *
        * The most common use of these is during traversal of the scene graph.
        * For instance, when traversing the scene graph the osg::NodeVisitor 
does a bitwise
        * AND of its TraversalMask with the Node's NodeMask to
        * determine if the Node should be processed/traversed.
        *
        * For example, if a Node has a NodeMask value of 0x02 (only 2nd bit set)
        * and the osg::Camera has a CullMask of 0x4 (2nd bit not set) then 
during cull traversal,
        * which takes it's TraversalMask from the Camera's CullMask, the node 
and any children
        * would be ignored and thereby treated as "culled" and thus not 
rendered.
        * Conversely, if the osg::Camera CullMask were 0x3 (2nd bit set) then 
the node
        * would be processed and child Nodes would be examined.
        */
        typedef unsigned int NodeMask;
        /** Set the node mask.*/
        inline void setNodeMask(NodeMask nm) { _nodeMask = nm; }
        /** Get the node mask.*/
        inline NodeMask getNodeMask() const { return _nodeMask; }


        /** A vector of std::string's which are used to describe the object.*/
        typedef std::vector<std::string> DescriptionList;

        /** Set the description list of the node.*/        
        inline void setDescriptions(const DescriptionList& descriptions) {
            getOrCreateProperty<DescriptionList>("osg.desc")->set(descriptions);
        }

        /** Get the description list of the node.*/        
        inline DescriptionList& getDescriptions() {
            return getOrCreateProperty<DescriptionList>("osg.desc")->get();
        }

        /** Get the const description list of the const node.*/        
        inline const DescriptionList& getDescriptions() const {
            return getOrCreateProperty<DescriptionList>("osg.desc")->get();
        }

        /** Get a single const description of the const node.*/
        inline const std::string& getDescription(unsigned int i) const {
            return getOrCreateProperty<DescriptionList>("osg.desc")->get()[i];
        }

        /** Get a single description of the node.*/
        inline std::string& getDescription(unsigned int i) {
            return getOrCreateProperty<DescriptionList>("osg.desc")->get()[i];
        }

        /** Get the number of descriptions of the node.*/
        inline size_t getNumDescriptions() const {
            if (!_properties.valid()) {
                return 0;
            }
            return 
getOrCreateProperty<DescriptionList>("osg.desc")->get().size();
        }

        /** Add a description string to the node.*/
        void addDescription(const std::string& desc) {
            
getOrCreateProperty<DescriptionList>("osg.desc")->get().push_back(desc);
        }


        /** Set the node's StateSet.*/
        void setStateSet(osg::StateSet* stateset);

        /** return the node's StateSet, if one does not already exist create it
          * set the node and return the newly created StateSet. This ensures
          * that a valid StateSet is always returned and can be used directly.*/
        osg::StateSet* getOrCreateStateSet();

        /** Return the node's StateSet. returns NULL if a stateset is not 
attached.*/
        inline osg::StateSet* getStateSet() { return _stateset.get(); }

        /** Return the node's const StateSet. Returns NULL if a stateset is not 
attached.*/
        inline const osg::StateSet* getStateSet() const { return 
_stateset.get(); }

        /** Set the initial bounding volume to use when computing the overall 
bounding volume.*/
        void setInitialBound(const osg::BoundingSphere& bsphere) { 
_initialBound = bsphere; dirtyBound(); }

        /** Set the initial bounding volume to use when computing the overall 
bounding volume.*/
        const BoundingSphere& getInitialBound() const { return _initialBound; }

        /** Mark this node's bounding sphere dirty.
            Forcing it to be computed on the next call to getBound().*/
        void dirtyBound();

        /** Get the bounding sphere of node.
           Using lazy evaluation computes the bounding sphere if it is 
'dirty'.*/
        inline const BoundingSphere& getBound() const
        {
            if(!_boundingSphereComputed)
            {
                _boundingSphere = _initialBound;
                if (_computeBoundCallback.valid()) 
                    
_boundingSphere.expandBy(_computeBoundCallback->computeBound(*this));
                else
                    _boundingSphere.expandBy(computeBound());
                    
                _boundingSphereComputed = true;
            }
            return _boundingSphere;
        }


        /** Compute the bounding sphere around Node's geometry or children.
            This method is automatically called by getBound() when the bounding
            sphere has been marked dirty via dirtyBound().*/
        virtual BoundingSphere computeBound() const;

        /** Callback to allow users to override the default computation of 
bounding volume.*/
        struct ComputeBoundingSphereCallback : public osg::Object
        {
            ComputeBoundingSphereCallback() {}

            ComputeBoundingSphereCallback(const 
ComputeBoundingSphereCallback&,const CopyOp&) {}

            META_Object(osg,ComputeBoundingSphereCallback);

           virtual BoundingSphere computeBound(const osg::Node&) const { return 
BoundingSphere(); }
        };

        /** Set the compute bound callback to override the default 
computeBound.*/
        void setComputeBoundingSphereCallback(ComputeBoundingSphereCallback* 
callback) { _computeBoundCallback = callback; }

        /** Get the compute bound callback.*/
        ComputeBoundingSphereCallback* getComputeBoundingSphereCallback() { 
return _computeBoundCallback.get(); }

        /** Get the const compute bound callback.*/
        const ComputeBoundingSphereCallback* getComputeBoundingSphereCallback() 
const { return _computeBoundCallback.get(); }

        /** Set whether to use a mutex to ensure ref() and unref() are thread 
safe.*/
        virtual void setThreadSafeRefUnref(bool threadSafe);

        /** Resize any per context GLObject buffers to specified size. */
        virtual void resizeGLObjectBuffers(unsigned int /*maxSize*/);

        /** If State is non-zero, this function releases any associated OpenGL 
objects for
           * the specified graphics context. Otherwise, releases OpenGL objects
           * for all graphics contexts. */
        virtual void releaseGLObjects(osg::State* = 0) const;


    protected:

        /** Node destructor. Note, is protected so that Nodes cannot
            be deleted other than by being dereferenced and the reference
            count being zero (see osg::Referenced), preventing the deletion
            of nodes which are still in use. This also means that
            Nodes cannot be created on stack i.e Node node will not compile,
            forcing all nodes to be created on the heap i.e Node* node
            = new Node().*/
        virtual ~Node();



        BoundingSphere                          _initialBound;
        ref_ptr<ComputeBoundingSphereCallback>  _computeBoundCallback;
        mutable BoundingSphere                  _boundingSphere;
        mutable bool                            _boundingSphereComputed;

        void addParent(osg::Group* node);
        void removeParent(osg::Group* node);

        ParentList _parents;
        friend class osg::Group;
        friend class osg::Drawable;
        friend class osg::StateSet;

        ref_ptr<NodeCallback> _updateCallback;
        unsigned int _numChildrenRequiringUpdateTraversal;
        void setNumChildrenRequiringUpdateTraversal(unsigned int num);

        ref_ptr<NodeCallback> _eventCallback;
        unsigned int _numChildrenRequiringEventTraversal;
        void setNumChildrenRequiringEventTraversal(unsigned int num);

        ref_ptr<NodeCallback> _cullCallback;

        bool _cullingActive;
        unsigned int _numChildrenWithCullingDisabled;        
        void setNumChildrenWithCullingDisabled(unsigned int num);

        unsigned int _numChildrenWithOccluderNodes;        
        void setNumChildrenWithOccluderNodes(unsigned int num);

        NodeMask _nodeMask;
        
        ref_ptr<StateSet> _stateset;
};

}

#endif
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
 *
 * This library is open source and may be redistributed and/or modified under  
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 * OpenSceneGraph Public License for more details.
*/

#ifndef OSG_OBJECT
#define OSG_OBJECT 1

#include <osg/Referenced>
#include <osg/CopyOp>
#include <osg/Property>
#include <osg/ref_ptr>

#include <string>

namespace osg {

// forward declare
class State;

#define _ADDQUOTES(def) #def
#define ADDQUOTES(def) _ADDQUOTES(def)

/** META_Object macro define the standard clone, isSameKindAs and className 
methods.
  * Use when subclassing from Object to make it more convenient to define 
  * the standard pure virtual clone, isSameKindAs and className methods 
  * which are required for all Object subclasses.*/
#define META_Object(library,name) \
        virtual osg::Object* cloneType() const { return new name (); } \
        virtual osg::Object* clone(const osg::CopyOp& copyop) const { return 
new name (*this,copyop); } \
        virtual bool isSameKindAs(const osg::Object* obj) const { return 
dynamic_cast<const name *>(obj)!=NULL; } \
        virtual const char* libraryName() const { return #library; }\
        virtual const char* className() const { return #name; }

template<typename T>
T* clone(const T* t, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY)
{
    return dynamic_cast<T*>(t->clone(copyop)); 
}


template<typename T>
T* clone(const T* t, const std::string& name, const osg::CopyOp& 
copyop=osg::CopyOp::SHALLOW_COPY)
{
    T* newObject = dynamic_cast<T*>(t->clone(copyop)); 
    newObject->setName(name);
    return newObject;
}

/**
 * Base class/standard interface for objects which require IO support, 
 * cloning and reference counting.
 * Based on GOF Composite, Prototype and Template Method patterns.
 */
class OSG_EXPORT Object : public Referenced
{
    public:
        /**
         * Construct an object. Note Object is a pure virtual base class
         * and therefore cannot be constructed on its own, only derived
         * classes which override the clone and className methods are
         * concrete classes and can be constructed.
         * */
        inline Object() : Referenced(), _dataVariance(UNSPECIFIED) {}

        inline explicit Object(bool threadSafeRefUnref) : 
Referenced(threadSafeRefUnref), _dataVariance(UNSPECIFIED) {}

        /** Copy constructor, optional CopyOp object can be used to control
         * shallow vs deep copying of dynamic data.
         */
        Object(const Object&, const CopyOp& copyop = CopyOp::SHALLOW_COPY);

        /**
         * Clone the type of an object, with Object* return type.
         * Must be defined by derived classes.
         */
        virtual Object* cloneType() const = 0;

        /**
         * Clone an object, with Object* return type.
         * Must be defined by derived classes.
         */
        virtual Object* clone(const CopyOp&) const = 0;

        virtual bool isSameKindAs(const Object*) const { return true; }

        /**
         * Return the name of the object's library. Must be defined
         * by derived classes. The OpenSceneGraph convention is that the
         * namespace of a library is the same as the library name.
         */
        virtual const char* libraryName() const = 0;

        /**
         * Return the name of the object's class type. Must be defined
         * by derived classes.
         */
        virtual const char* className() const = 0;
        

        /// Set the object name using C++ style string.
        inline void setName( const std::string& name ) { _name = name; }

        /// Set the object name using a C style string.
        inline void setName( const char* name )
        {
            if (name) _name = name;
            else _name.clear();
        }

        /// Get the object name.
        inline const std::string& getName() const { return _name; }


        /**
         * Data variance.
         * The DataVariance value can be used by routines such as optimization 
codes that wish to share static data.
         */
        enum DataVariance
        {
            DYNAMIC,    ///< Values that vary over the lifetime of the object.
            STATIC,     ///< Values that do not change over the lifetime of the 
object.
            UNSPECIFIED ///< Data variance hasn't been set yet.
        };
        
        /// Set the data variance of this object.
        inline void setDataVariance(DataVariance dv) { _dataVariance = dv; }

        /// Get the data variance of this object.
        inline DataVariance getDataVariance() const { return _dataVariance; }
        
        /// Compute the DataVariance based on an assessment of callback etc.
        virtual void computeDataVariance() {}


        /**
         * Object properties.
         * Properties can be used to associate application-specific data with 
an object.
         * Data must be derived from Referenced for proper memeory-management.
         * OSG is using a "osg." prefix to its internal data and applications 
are
         * encouraged to follow this pattern to avoid name conflicts.
         */

        /**
         * Sets a typed property by name.
         * Specialization for 'Referenced'...
         */
        inline void setProperty(const std::string& name, Referenced* prop) {
            if (!_properties.valid()) {
                _properties = ref_ptr<PropertyMap>(new PropertyMap);
            }
            _properties->set(name, prop);
        }

        /**
         * Sets a typed property by name.
         * This convenience function will create a new Property<T> and store
         * it under the given name.
         */
        template <typename T>
        inline void setProperty(const std::string& name, const T& value) {
            if (!_properties.valid()) {
                _properties = ref_ptr<PropertyMap>(new PropertyMap);
            }
            _properties->set(name, new Property<T>(value));
        }

        /// Clears a property by name.
        inline void clearProperty(const std::string& name) {
            if (_properties.valid()) {
                _properties->clear(name);
            }
        }

        /**
         * Gets a const property by name.
         * Specialization for 'Referenced'...
         */
        inline const Referenced* getProperty(const std::string& name) const {
            if (!_properties.valid()) {
                return NULL;
            }
            return _properties->get(name);
        }

        /**
         * Gets a property by name.
         * Specialization for 'Referenced'...
         */
        inline Referenced* getProperty(const std::string& name) {
            if (!_properties.valid()) {
                return NULL;
            }
            return _properties->get(name);
        }

        /**
         * Gets a const typed property by name.
         * Get property by name and cast it to const Property<T>.
         * @return NULL when not found or not of the proper type, else the 
const property.
         */
        template <typename T>
        inline const Property<T>* getProperty(const std::string& name) const {
            return dynamic_cast<const Property<T>*>(getProperty(name));
        }

        /**
         * Gets a typed property by name.
         * Get property by name and cast it to Property<T>.
         * @return 0 when not found or not of the proper type, else the 
property.
         */
        template <typename T>
        inline Property<T>* getProperty(const std::string& name) {
            return dynamic_cast<Property<T>*>(getProperty(name));
        }

        /**
         * Tries to get a typed property by name.
         * @return false when not found, else true and the value is valid.
         */
        template <typename T>
        bool tryGetProperty(const std::string& name, T& value) {
            Property<T>* prop = getProperty<T>(name);
            if (!prop) {
                return false;
            }

            value = prop->get();
            return true;
        }


        /**
         * Gets or creates a typed property by name.
         * Note: For backwards compatibility this is 'const' (and _properties 
is mutable)
         * so that the 'const' versions of Node::getDescription*() still works.
         * @return 0 when not found or not of the proper type, else the 
property.
         */
        template <typename T>
        inline Property<T>* getOrCreateProperty(const std::string& name) const {

            if (!_properties.valid()) {
                _properties = ref_ptr<PropertyMap>(new PropertyMap);
            }

            PropertyMap::iterator it = _properties->find(name);
            if (it == _properties->end()) {
                // create property
                Property<T>* obj = new Property<T>();
                (*_properties)[name] = ref_ptr< Property<T> >(obj);
                return obj;
            }

            // existing property
            return dynamic_cast<Property<T>*>(it->second.get());
        }


        /**
         * Set user data.
         * Data must be subclassed from Referenced to allow reference counting.
         * If your data isn't directly subclassed from Referenced, create an 
adapter object
         * which points to your own object and handles the memory addressing.
         */
        inline void setUserData(Referenced* obj) {
            setProperty("osg.data", obj);
        }
        
        /// Get user data.
        inline Referenced* getUserData() {
            return getProperty("osg.data");
        }
        
        /// Get const user data.
        inline const Referenced* getUserData() const {
            return getProperty("osg.data");
        }


        /// Resize any per context GLObject buffers to specified size.
        virtual void resizeGLObjectBuffers(unsigned int /*maxSize*/) {}

        /**
         * If State is non-zero, this function releases any associated OpenGL 
objects for
         * the specified graphics context. Otherwise, releases OpenGL objects
         * for all graphics contexts.
         */
        virtual void releaseGLObjects(osg::State* = 0) const {}

    protected:

        /**
         * Object destructor. Note, is protected so that Objects cannot
         * be deleted other than by being dereferenced and the reference
         * count being zero (see osg::Referenced), preventing the deletion
         * of nodes which are still in use. This also means that
         * Nodes cannot be created on stack i.e Node node will not compile,
         * forcing all nodes to be created on the heap i.e Node* node = new 
Node().
         */
        virtual ~Object() {}
        
        std::string _name;
        DataVariance _dataVariance;
        mutable ref_ptr<PropertyMap> _properties;

    private:

        /// disallow any copy operator.
        Object& operator = (const Object&) { return *this; }
};

}

#endif
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2009 Robert Osfield 
 *
 * This library is open source and may be redistributed and/or modified under  
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 * OpenSceneGraph Public License for more details.
 */

#ifndef OSG_PROPERTY
#define OSG_PROPERTY 1

#include <osg/Export>
#include <osg/Referenced>
#include <osg/ref_ptr>

#include <string>
#include <vector>
#include <map>


namespace osg {

    /**
     * Property template.
     */
    template <typename T>
    class OSG_EXPORT Property : public Referenced
    {
        typedef Property<T> data_type;

    public:
        Property() : _data() {}
        Property(const data_type& other) : _data(other._data) {}
        Property(const T& data) : _data(data) {}

        /// Setter.
        void set(const T& data) { _data = data; }

        /// Getter.
        const T& get() const { return _data; }
        T& get() { return _data; }

        /// Assignment operators.
        data_type& operator=(const data_type& other) { _data = other._data; 
return *this; }
        data_type& operator=(T data) { _data = data; return *this; }

        /// Comparision.
        bool operator==(const data_type& other) const { return (_data == 
other._data); }
        bool operator==(T data) const { return (_data == data); }

        bool operator!=(const data_type& other) const { return (_data != 
other._data); }
        bool operator!=(T data) const { return (_data != data); }

        /// Output conversion.
        operator T() const { return _data; }

    private:
        T _data;
    };

    /**
     * Map of properties.
     * Properties must be derived from Referenced.
     */
    class OSG_EXPORT PropertyMap : public Referenced, public 
std::map<std::string, ref_ptr<Referenced> >
    {
    public:
        PropertyMap() {}
#if 0 && REVIEW_COPYOP
        PropertyMap(const PropertyMap& obj, const CopyOp& copyop) : 
Referenced() {
            for (iterator it = begin(); it != end(); ++it) {
                //(*this)[it->first] = copyop(it->second);
            }
        }
#endif

        /// Set property by name.
        inline void set(const std::string& name, Referenced* prop) {
            (*this)[name] = prop;
        }

        /// Clear property by name.
        inline void clear(const std::string& name) {
            iterator it = find(name);
            if (it != end()) {
                erase(it);
            }
        }

        /**
         * Get property by name.
         * @return Referenced*, or 0 if not found.
         */
        inline Referenced* get(const std::string& name) {
            iterator it = find(name);
            if (it == end()) {
                return 0;
            }
            return it->second.get();
        }

        /**
         * Get const property by name.
         * @return const Referenced*, or 0 if not found.
         */
        inline const Referenced* get(const std::string& name) const {
            const_iterator it = find(name);
            if (it == end()) {
                return 0;
            }
            return it->second.get();
        }

    private:
    };

} // namespace

#endif
_______________________________________________
osg-users mailing list
[email protected]
http://lists.openscenegraph.org/listinfo.cgi/osg-users-openscenegraph.org

Reply via email to