Added a bunch of files synched with 0.8.42

This commit is contained in:
Don BURNS
2001-09-19 21:08:56 +00:00
parent fed86f3f03
commit e8f256a59d
446 changed files with 58397 additions and 10552 deletions

View File

@@ -1,18 +1,30 @@
#ifndef OSG_ALPHAFUNC
#define OSG_ALPHAFUNC 1
#include <osg/Export>
#include <osg/Object>
#include <osg/GL>
#include <osg/StateAttribute>
#include <osg/StateSet>
namespace osg {
/** Encapsulte OpenGL glAlphaFunc.
*/
class SG_EXPORT AlphaFunc : public Object
class SG_EXPORT AlphaFunc : public StateAttribute
{
public :
AlphaFunc();
virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const AlphaFunc*>(obj)!=0L; }
virtual Object* clone() const { return new AlphaFunc(); }
virtual const char* className() const { return "AlphaFunc"; }
virtual const Type getType() const { return ALPHAFUNC; }
virtual void setStateSetModes(StateSet& ds,const GLModeValue value) const
{
ds.setMode(GL_ALPHA_TEST,value);
}
enum ComparisonFunction {
NEVER = GL_NEVER,
LESS = GL_LESS,
@@ -23,38 +35,23 @@ class SG_EXPORT AlphaFunc : public Object
GEQUAL = GL_GEQUAL,
ALWAYS = GL_ALWAYS
};
AlphaFunc();
static AlphaFunc* instance();
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<AlphaFunc*>(obj)!=NULL; }
virtual Object* clone() const { return new AlphaFunc(); }
virtual const char* className() const { return "AlphaFunc"; }
void setFunction(ComparisonFunction func,float ref)
inline void setFunction(const ComparisonFunction func,const float ref)
{
_comparisonFunc = func;
_referenceValue = ref;
}
ComparisonFunction getFunction() const { return _comparisonFunc; }
inline const ComparisonFunction getFunction() const { return _comparisonFunc; }
float getRefrenceValue() const { return _referenceValue; }
static void enable();
static void disable();
void apply();
inline const float getReferenceValue() const { return _referenceValue; }
virtual void apply(State& state) const;
protected:
virtual ~AlphaFunc();
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
bool matchFuncStr(const char* str,ComparisonFunction& func);
const char* getFuncStr(ComparisonFunction func);
ComparisonFunction _comparisonFunc;
float _referenceValue;

View File

@@ -1,11 +1,12 @@
#ifndef OSG_BILLBOARD
#define OSG_BILLBOARD 1
#include <osg/Matrix>
#include <osg/Geode>
namespace osg {
/** Billboard - a Geode which orientates its child osg::GeoSet's to face
/** Billboard - a Geode which orientates its child osg::Drawable's to face
the eye point.
Typical uses are for trees, or particle explosions.
*/
@@ -22,56 +23,66 @@ class SG_EXPORT Billboard : public Geode
Billboard();
virtual Object* clone() const { return new Billboard(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<Billboard*>(obj)!=NULL; }
virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const Billboard*>(obj)!=NULL; }
virtual const char* className() const { return "Billboard"; }
virtual void accept(NodeVisitor& nv) { nv.apply(*this); }
void setAxis(const Vec3& axis) { _axis = axis; }
void getAxis(Vec3& axis) const { axis = _axis; }
/** Set the axis about which all the billboard's drawable rotate. */
inline void setAxis(const Vec3& axis) { _axis = axis; }
/** Get the axis about which all the billboard's drawable rotate. */
inline const Vec3& getAxis() const { return _axis; }
void setMode(Mode mode) { _mode = mode; }
int getMode() const { return _mode; }
/** Set the billboard rotation mode. */
inline void setMode(const Mode mode) { _mode = mode; }
/** Get the billboard rotation mode. */
inline const Mode getMode() const { return _mode; }
void setPos(int i,const Vec3& pos) { _positionList[i] = pos; }
void getPos(int i,Vec3& pos) const { pos = _positionList[i]; }
/** Set the position of specified drawable. */
inline void setPos(int i,const Vec3& pos) { _positionList[i] = pos; }
/** Get the position of specified drawable. */
inline const Vec3& getPos(int i) const { return _positionList[i]; }
/** Add GeoSet to Billboard with default position(0,0,0);
/** PositionList represents a list of pivot points for each drawable.*/
typedef std::vector<Vec3> PositionList;
/** Get the PostionList from the billboard.*/
inline PositionList& getPositionList() { return _positionList; }
/** Get a const PostionList from the billboard.*/
inline const PositionList& getPositionList() const { return _positionList; }
/** Add Drawable to Billboard with default position(0,0,0);
* If gset not NULL and is not contained in Billboard then increment its
* reference count, and dirty the bounding box to cause it to recompute on
* next getBound() and return true for success. Otherwise return false.
*/
virtual bool addGeoSet( GeoSet *gset );
virtual const bool addDrawable( Drawable *gset );
/** Add GeoSet to Geode at position pos.
/** Add Drawable to Geode at position pos.
* If gset not NULL and is not contained in Billboard then increment its
* reference count, and dirty the bounding box to cause it to recompute on
* next getBound() and return true for success. Otherwise return false.
*/
virtual bool addGeoSet(GeoSet *gset,const Vec3& pos);
virtual const bool addDrawable(Drawable *gset,const Vec3& pos);
/** Remove GeoSet and associated position from Billboard.
/** Remove Drawable and associated position from Billboard.
* If gset is contained in Billboard then remove it from the geoset
* list and decrement its reference count, and dirty the
* bounding box to cause it to recompute on next getBound() and
* return true for success. If gset is not found then return false
* and do not the reference count of gset is left unchanged.
*/
virtual bool removeGeoSet( GeoSet *gset );
virtual const bool removeDrawable( Drawable *gset );
void calcRotation(const Vec3& eye_local, const Vec3& pos_local,Matrix& mat);
void calcTransform(const Vec3& eye_local, const Vec3& pos_local,Matrix& mat);
void calcRotation(const Vec3& eye_local, const Vec3& pos_local,Matrix& mat) const;
void calcTransform(const Vec3& eye_local, const Vec3& pos_local,Matrix& mat) const;
protected:
virtual ~Billboard();
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
virtual bool computeBound( void );
virtual const bool computeBound() const;
typedef std::vector<Vec3> PositionList;
Mode _mode;
Vec3 _axis;

View File

@@ -29,7 +29,7 @@ class SG_EXPORT BoundingBox
_max(-FLT_MAX,-FLT_MAX,-FLT_MAX) {}
/** initialize to invalid values to represent an unset bounding box.*/
void init()
inline void init()
{
_min.set(FLT_MAX,FLT_MAX,FLT_MAX);
_max.set(-FLT_MAX,-FLT_MAX,-FLT_MAX);
@@ -37,44 +37,44 @@ class SG_EXPORT BoundingBox
/** return true if the bounding box contains valid values,
false if the bounding box is effectively unset/empty.*/
bool isValid() const
inline const bool isValid() const
{
return _max.x()>=_min.x();
}
float& xMin() { return _min.x(); }
float xMin() const { return _min.x(); }
inline float& xMin() { return _min.x(); }
inline const float xMin() const { return _min.x(); }
float& yMin() { return _min.y(); }
float yMin() const { return _min.y(); }
inline float& yMin() { return _min.y(); }
inline const float yMin() const { return _min.y(); }
float& zMin() { return _min.z(); }
float zMin() const { return _min.z(); }
inline float& zMin() { return _min.z(); }
inline const float zMin() const { return _min.z(); }
float& xMax() { return _max.x(); }
float xMax() const { return _max.x(); }
inline float& xMax() { return _max.x(); }
inline const float xMax() const { return _max.x(); }
float& yMax() { return _max.y(); }
float yMax() const { return _max.y(); }
inline float& yMax() { return _max.y(); }
inline const float yMax() const { return _max.y(); }
float& zMax() { return _max.z(); }
float zMax() const { return _max.z(); }
inline float& zMax() { return _max.z(); }
inline const float zMax() const { return _max.z(); }
/** Calculate and return the center of the bounding box.*/
Vec3 center() const
inline const Vec3 center() const
{
return (_min+_max)*0.5f;
}
/** Calculate and return the radius of the bounding box.*/
float radius() const
inline const float radius() const
{
return sqrtf(radius2());
}
/** Calculate and return the radius squared of the bounding box.
Note, radius2() is faster to calculate than radius().*/
float radius2() const
inline const float radius2() const
{
return 0.25f*((_max-_min).length2());
}
@@ -84,7 +84,7 @@ class SG_EXPORT BoundingBox
the first bit toggles between x min and x max, second
bit toggles between y min and y max, third bit toggles
between z min and z max.*/
Vec3 corner(unsigned int pos) const
inline const Vec3 corner(unsigned int pos) const
{
return Vec3(pos&1?_max.x():_min.x(),pos&2?_max.y():_min.y(),pos&4?_max.z():_min.z());
}
@@ -102,7 +102,7 @@ class SG_EXPORT BoundingBox
void expandBy(const BoundingSphere& sh);
/** return true is vertex v is within the box.*/
bool contains(const Vec3& v)
inline const bool contains(const Vec3& v) const
{
return isValid() &&
(v.x()>=_min.x() && v.x()<=_max.x()) &&

View File

@@ -23,7 +23,7 @@ class SG_EXPORT BoundingSphere
BoundingSphere() : _center(0.0f,0.0f,0.0f),_radius(-1.0f) {}
/** initialize to invalid values to represent an unset bounding sphere.*/
void init()
inline void init()
{
_center.set(0.0f,0.0f,0.0f);
_radius = -1.0f;
@@ -31,24 +31,25 @@ class SG_EXPORT BoundingSphere
/** return true if the bounding sphere contains valid values,
false if the bounding sphere is effectively unset.*/
bool isValid() const { return _radius>=0.0f; }
inline const bool isValid() const { return _radius>=0.0f; }
/** return the const center of the bounding sphere.*/
const Vec3& center() const { return _center; }
/** return the center of the bounding sphere.*/
Vec3& center() { return _center; }
inline Vec3& center() { return _center; }
/** return the const center of the bounding sphere.*/
inline const Vec3& center() const { return _center; }
/** return the radius of the bounding sphere.*/
inline float& radius() { return _radius; }
/** return the const radius of the bounding sphere.*/
float radius() const { return _radius; }
/** return the radius of the bounding sphere.*/
float& radius() { return _radius; }
inline const float radius() const { return _radius; }
/** return the radius squared.
Note, for performance reasons, assumes the calling method has ensured
that the sphere is valid before calling radius2(), i.e. has _radius>=0.0,
as it does not check th validity of sphere and will eroneously return a positive value.*/
float radius2() const { return _radius*_radius; }
inline const float radius2() const { return _radius*_radius; }
/** If the vertex is outwith the sphere expand to ecompass vertex.
Calculates the combination of movement of center and radius which
@@ -73,11 +74,18 @@ class SG_EXPORT BoundingSphere
void expandRadiusBy(const BoundingSphere& sh);
/** return true is vertex v is within the sphere.*/
bool contains(const Vec3& v)
inline const bool contains(const Vec3& v) const
{
return isValid() && ((v-_center).length2()<=radius2());
}
/** return true if bounding sphere's intersect each other.*/
inline const bool intersects( const BoundingSphere& bs ) const
{
return isValid() && bs.isValid() &&
((_center - bs._center).length2() <= (_radius + bs._radius)*(_radius + bs._radius));
}
};
};

View File

@@ -1,17 +1,19 @@
#ifndef OSG_CAMERA
#define OSG_CAMERA 1
#include <osg/Export>
#include <osg/Scene>
#include <osg/ref_ptr>
#include <osg/Referenced>
#include <osg/Matrix>
#include <osg/Quat>
#include <osg/ClippingVolume>
namespace osg {
/** Camera class for encapsulating the view position and orientation.
* This is the first implementation of osg::Camera class and
* currently is a perspective camera, but in future will be
* a base class from which PerpsectivCamera,FrustumCamera and OrthoCamera
* will be derived.
*/
/** Camera class for encapsulating the view position and orientation and
* projection (lens) used. Creates a projection and modelview matrices
* which can be used to set OpenGL's PROJECTION and MODELVIEW matrices
* represectively.
*/
class SG_EXPORT Camera: public osg::Referenced
{
@@ -20,19 +22,91 @@ class SG_EXPORT Camera: public osg::Referenced
Camera();
virtual ~Camera();
/** Range of projection types.
* OTHO2D is a special case of OTHO where the near and far planes
* are equal to -1 and 1 respectively.
* PRESPECTIVE is a special case of FRUSTUM where the left & right
* and bottom and top and symetrical.*/
enum ProjectionType
{
ORTHO,
ORTHO2D,
FRUSTUM,
PERSPECTIVE
};
/** Get the projection type set by setOtho,setOtho2D,setFrustum,
* and set perspective methods.*/
const ProjectionType getProjectionType() const { return _projectionType; }
/** Set a orthographics projection. See glOrtho for further details.*/
void setOrtho(const double left, const double right,
const double bottom, const double top,
const double zNear, const double zFar);
/** Set a 2D orthographics projection. See gluOrtho2D for further details.*/
void setOrtho2D(const double left, const double right,
const double bottom, const double top);
/** Set a perspective projection. See glFrustum for further details.*/
void setFrustum(const double left, const double right,
const double bottom, const double top,
const double zNear, const double zFar);
/** Set a sysmetical perspective projection, See gluPerspective for further details.
* Aspect ratio is defined as width/height.*/
void setPerspective(const double fovy,const double aspectRatio,
const double zNear, const double zFar);
/**
* Set field of view and window aspect ratio.
* The parameters have the same meaning as their counterparts
* in gluPerspective(fovy,aspectRatio
*/
void setFieldOfView(double fovy,double aspectRatio);
void setFieldOfViewY(double fovy) { _fovy = fovy; }
double getFieldOfViewY() const { return _fovy; }
/** Set the near and far clipping planes.*/
void setNearFar(const double zNear, const double zFar);
void setAspectRatio(double aspectRatio) { _aspectRatio = aspectRatio; }
double getAspectRatio() const { return _aspectRatio; }
/** Use in combination with adjustAspectRatio, to control
* the change in frustum clipping planes to account for
* changes in windows aspect ratio,*/
enum AdjustAxis
{
ADJUST_VERTICAL,
ADJUST_HORIZONTAL
};
/** Adjust the clipping planes to account for a new window aspcect ratio.
* Typicall used after resizeing a window. Aspect ratio is defined as
* width/height.*/
void adjustAspectRatio(const double newAspectRatio, const AdjustAxis aa = ADJUST_HORIZONTAL);
const double left() const;
const double right() const;
const double top() const;
const double bottom() const;
const double zNear() const;
const double zFar() const;
/** Calculate and return the equivilant fovx for the current project setting.
* This value is only valid for when a symetric persepctive projection exists.
* i.e. getProjectionType()==PERSPECTIVE.*/
const double calc_fovy() const;
/** Calculate and return the equivilant fovy for the current project setting.
* This value is only valid for when a symetric persepctive projection exists.
* i.e. getProjectionType()==PERSPECTIVE.*/
const double calc_fovx() const;
/** Calculate and return the projection aspect ratio.
* Aspect ratio is defined as width/height.*/
const double calc_aspectRatio() const;
const Matrix& getProjectionMatrix() const;
enum LookAtType
{
USE_HOME_POSITON,
USE_EYE_AND_QUATERNION,
USE_EYE_CENTER_AND_UP
};
const LookAtType getLookAtType() const { return _lookAtType; }
/**
* hardwired home view for now, looking straight down the
@@ -41,96 +115,171 @@ class SG_EXPORT Camera: public osg::Referenced
void home();
/**
* Set the View, the up vector should be orthogonal to the
* look vector.
*/
void setView(Vec3 eyePoint,
Vec3 lookPoint,
Vec3 upVector);
* Set the View, the up vector should be orthogonal to the look vector.
* setView is now mapped to setLookAt(eye,center,up), and is only
* kept for backwards compatibility.
*/
void setView(const Vec3& eyePoint,
const Vec3& lookPoint,
const Vec3& upVector);
/** set the position and orientaion of the camera, using the same convention as
* gluLookAt.
*/
void setLookAt(const Vec3& eye,
const Vec3& center,
const Vec3& up);
/** set the position and orientaion of the camera, using the same convention as
* gluLookAt.
*/
void setLookAt(const double eyeX, const double eyeY, const double eyeZ,
const double centerX, const double centerY, const double centerZ,
const double upX, const double upY, const double upZ);
/** post multiple the existing eye point and orientation by matrix.
* note, does not affect any ModelTransforms that are applied.*/
void transformLookAt(const Matrix& matrix);
void ensureOrthogonalUpVector();
/** get the eyepoint. */
const Vec3& getEyePoint() const {return _eyePoint;}
/** get the eye point. */
inline const Vec3& getEyePoint() const { return _eye; }
/** get the lookpoint. */
const Vec3& getLookPoint() const {return _lookPoint;}
/** get the center point. */
inline const Vec3& getCenterPoint() const { return _center; }
/** which way is up? */
const Vec3& getUpVector() const {return _upVector;}
/** calculate side vector.*/
Vec3 getSideVector() const
{
Vec3 sv = (_lookPoint-_eyePoint)^_upVector;
sv.normalize();
return sv;
}
/** get the up vector */
inline const Vec3& getUpVector() const { return _up; }
/** calculate look vector.*/
Vec3 getLookVector() const
const Vec3 getLookVector() const;
/** calculate side vector.*/
const Vec3 getSideVector() const;
/** get focal distance.*/
inline const float getFocalLength() const { return _focalLength; }
enum TransformMode
{
Vec3 lv = (_lookPoint-_eyePoint);
lv.normalize();
return lv;
}
EYE_TO_MODEL,
MODEL_TO_EYE,
NO_ATTACHED_TRANSFORM
};
/** calculate focal distance.*/
float getFocalDistance() const
{
return (_lookPoint-_eyePoint).length();
}
/** Attach a transform matrix which is applied after the camera look at.
* The attached matrix can work in two ways, either as transform of the eye
* into the model coordinates - EYE_TO_MODEL, or as a transform of the
* model to the eye - MODEL_TO_EYE. The former is equivilant to attaching
* a camera internal to the scene graph. The later is equivilant to adding
* a osg::Transform at root of the scene to move the scene to the eye point.
* Typical used in conjunction with the LookAt position set to home,
* in which case it is simply treated as a model view matrix.
* If the same behaviour as IRIS Performer's setViewMat is desired
* then set the LookAt to be (0,0,0),(0,1,0),(0,0,1) since Performer's
* default direction is along the y axis, unlike OpenGL and the default OSG.
* If modelTransfor is NULL then do not use any model transform - just use the
* basic LookAt values.
* note: Camera internals maintains the both EYE_TO_MODEL and MODEL_TO_EYE
* internally and ensures that they are the inverse of one another. However,
* if you modify the attached transform then you must call dirtyTransform, to
* allow the OSG to update matrices accordingly.*/
void attachTransform(const TransformMode mode, Matrix* modelTransform=0);
/** set the near plane. */
void setNearPlane(double nearPlane) {_nearPlane=nearPlane;}
/**get the near plane. */
double getNearPlane() const {return _nearPlane;}
/** set the far plane. */
void setFarPlane(double farPlane) {_farPlane=farPlane;}
/** get the far plane. */
double getFarPlane() const {return _farPlane;}
/** must be called after you modify an attachedTransform. */
void dirtyTransform();
Matrix* getTransform(const TransformMode mode);
const Matrix* getTransform(const TransformMode mode) const;
/** Set up the OpenGL GL_PROJECTION matrix.
Enters the GL_PROJECTION mode, sets up matrix, then
resets model GL_MODELVIEW, which is by OpenGL convention the default.*/
void draw_PROJECTION() const;
/** Set up the OpenGL GL_MODELVIEW matrix.
* Enters the GL_MODELVIEW mode, sets matrix to identity
* and then sets matrix up according to camera, eye point, center
* point and upvector.
*/
void draw_MODELVIEW() const;
const Vec3 getEyePoint_Model() const;
const Vec3 getCenterPoint_Model() const;
const Vec3 getLookVector_Model() const;
const Vec3 getUpVector_Model() const;
const Vec3 getSideVector_Model() const;
/** Get the ModelView matrix.
* If a ModelTransform is supplied then the ModelView matrix is
* created by multipling the current LookAt by ModelTransform.
* Otherwise it is simply created by using the current LookAt,
* equivialent to using gluLookAt.*/
const Matrix& getModelViewMatrix() const;
void setUseNearClippingPlane(const bool use);
const bool getUseNearClippingPlane() const { return _useNearClippingPlane; }
void setUseFarClippingPlane(const bool use);
const bool getUseFarClippingPlane() const { return _useFarClippingPlane; }
/** get the view frustum clipping in model coordinates */
const ClippingVolume& getClippingVolume() const;
/** post multiply a camera by matrix.*/
void mult(const Camera& camera,const Matrix& m);
/** pre multiply a camera by matrix.*/
void mult(const Matrix& m,const Camera& camera);
void ensureOrthogonalUpVector();
/** Map object coordinates into windows coordinates.
* Equivilant to gluProject(...). */
const bool project(const Vec3& obj,const int* viewport,Vec3& win) const;
/** Map window coordinates into object coordinates.
* Equivilant to gluUnProject(...). */
const bool unproject(const Vec3& win,const int* viewport,Vec3& obj) const;
private:
protected:
// Disallow copy construction & assignment (for now)
Camera(const Camera&);
Camera& operator=(const Camera&);
Vec3 _eyePoint;
Vec3 _lookPoint;
Vec3 _upVector;
// projection details.
ProjectionType _projectionType;
double _fovy;
double _aspectRatio;
// note, in Frustum/Perspective mode these values are scaled
// by the zNear from when they were initialised to ensure that
// subsequent changes in zNear do not affect them.
double _left;
double _right;
double _bottom;
double _top;
double _zNear;
double _zFar;
// look at details.
LookAtType _lookAtType;
Vec3 _eye;
Vec3 _center;
Vec3 _up;
double _focalLength;
TransformMode _attachedTransformMode;
ref_ptr<Matrix> _eyeToModelTransform;
ref_ptr<Matrix> _modelToEyeTransform;
// flags to determin if near and far clipping planes are required.
bool _useNearClippingPlane;
bool _useFarClippingPlane;
// cached matrix and clipping volume derived from above settings.
mutable bool _dirty;
mutable ref_ptr<Matrix> _projectionMatrix;
mutable ref_ptr<Matrix> _modelViewMatrix;
mutable ClippingVolume _clippingVolume;
mutable ref_ptr<Matrix> _MP;
mutable ref_ptr<Matrix> _inverseMP;
void calculateMatricesAndClippingVolume() const;
double _nearPlane; // No Dougal, these are small... but those...
double _farPlane; // are far away
};

View File

@@ -1,46 +1,45 @@
#ifndef OSG_CULLFACE
#define OSG_CULLFACE 1
#include <osg/Export>
#include <osg/Object>
#include <osg/GL>
#include <osg/StateAttribute>
#include <osg/StateSet>
namespace osg {
/** Class to globally enable/disable OpenGL's polygon culling mode
(GL_CULL_FACE).
/** Class to globally enable/disable OpenGL's polygon culling mode=.
*/
class SG_EXPORT CullFace : public Object
class SG_EXPORT CullFace : public StateAttribute
{
public :
CullFace();
virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const CullFace*>(obj)!=0L; }
virtual Object* clone() const { return new CullFace(); }
virtual const char* className() const { return "CullFace"; }
virtual const Type getType() const { return CULLFACE; }
virtual void setStateSetModes(StateSet& ds,const GLModeValue value) const
{
ds.setMode(GL_CULL_FACE,value);
}
enum Mode {
FRONT = GL_FRONT,
BACK = GL_BACK,
FRONT_AND_BACK = GL_FRONT_AND_BACK
};
CullFace();
static CullFace* instance();
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<CullFace*>(obj)!=NULL; }
virtual Object* clone() const { return new CullFace(); }
virtual const char* className() const { return "CullFace"; }
void setMode(Mode mode) { _mode = mode; }
/** Enable the polygon culling mode.*/
static void enable();
/** Disable the polygon culling mode.*/
static void disable();
inline void setMode(const Mode mode) { _mode = mode; }
void apply();
inline const Mode getMode() const { return _mode; }
virtual void apply(State& state) const;
protected:
virtual ~CullFace();
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
Mode _mode;

View File

@@ -5,18 +5,6 @@
#pragma warning( disable : 4251 )
#pragma warning( disable : 4275 )
#pragma warning( disable : 4786 )
/* Define NULL pointer value */
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#endif
#endif
#if defined(_MSC_VER)
@@ -29,4 +17,14 @@
# define SG_EXPORT
#endif
/* Define NULL pointer value */
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#endif
#endif

View File

@@ -1,60 +1,59 @@
#ifndef OSG_FOG
#define OSG_FOG 1
#include <osg/GL>
#include <osg/Vec4>
#include <osg/Types>
#include <osg/Object>
#include <osg/Vec4>
#include <osg/StateAttribute>
#include <osg/StateSet>
namespace osg {
/** Fog - encapsulates OpenGL fog state. */
class SG_EXPORT Fog : public Object
class SG_EXPORT Fog : public StateAttribute
{
public :
enum FogMode {
Fog();
virtual Object* clone() const { return new Fog(); }
virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const Fog*>(obj)!=NULL; }
virtual const char* className() const { return "Fog"; }
virtual const Type getType() const { return FOG; }
virtual void setStateSetModes(StateSet& ds,const GLModeValue value) const
{
ds.setMode(GL_FOG,value);
}
enum Mode {
LINEAR = GL_LINEAR,
EXP = GL_EXP,
EXP2 = GL_EXP2
};
Fog( void );
static Fog* instance();
virtual Object* clone() const { return new Fog(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<Fog*>(obj)!=NULL; }
virtual const char* className() const { return "Fog"; }
inline void setMode( const Mode mode ) { _mode = mode; }
inline Mode getMode() const { return _mode; }
static void enable( void );
static void disable( void );
void apply( void );
inline void setDensity( const float density ) { _density = density; }
inline const float getDensity() const { return _density; }
void setMode( uint mode ) { _mode = mode; }
uint getMode( void ) { return _mode; }
inline void setStart( const float start ) { _start = start; }
inline const float getStart() const { return _start; }
void setDensity( float density ) { _density = density; }
float getDensity( void ) { return _density; }
inline void setEnd( const float end ) { _end = end; }
inline const float getEnd() const { return _end; }
void setStart( float start ) { _start = start; }
float getStart( void ) { return _start; }
inline void setColor( const Vec4 &color ) { _color = color; }
inline const Vec4& getColor() const { return _color; }
void setEnd( float end ) { _end = end; }
float getEnd( void ) { return _end; }
void setColor( Vec4 &color )
{
_color[0] = color[0];
_color[1] = color[1];
_color[2] = color[2];
_color[3] = color[3];
}
virtual void apply(State& state) const;
protected :
virtual ~Fog( void );
virtual ~Fog();
uint _mode;
Mode _mode;
float _density;
float _start;
float _end;

View File

@@ -1,71 +1,62 @@
#ifndef OSG_GL
#define OSG_GL 1
#ifdef WIN32
#ifndef WIN32
// this works with no problems
// #ifndef _WINDOWS_
// #define WIN32_LEAN_AND_MEAN
// #include <windows.h>
// #endif
// non windows, doesn't require nonesense as seen below :-)
#ifndef __gl_h_
#include <GL/gl.h>
#endif
// follows lifted from glut.h, to avoid including <windows.h>
//#if defined(_WIN32)
// GLUT 3.7 now tries to avoid including <windows.h>
// to avoid name space pollution, but Win32's <GL/gl.h>
// needs APIENTRY and WINGDIAPI defined properly.
# if 0
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
# else
// XXX This is from Win32's <windef.h>
# ifndef APIENTRY
# define GLUT_APIENTRY_DEFINED
# if (_MSC_VER >= 800) || defined(_STDCALL_SUPPORTED)
# define APIENTRY __stdcall
# else
# define APIENTRY
# endif
# endif
// XXX This is from Win32's <winnt.h>
# ifndef CALLBACK
# if (defined(_M_MRX000) || defined(_M_IX86) || defined(_M_ALPHA) || defined(_M_PPC)) && !defined(MIDL_PASS)
# define CALLBACK __stdcall
# else
# define CALLBACK
# endif
# endif
// XXX This is from Win32's <wingdi.h> and <winnt.h>
# ifndef WINGDIAPI
# define GLUT_WINGDIAPI_DEFINED
# define WINGDIAPI __declspec(dllimport)
# endif
// XXX This is from Win32's <ctype.h>
# ifndef _WCHAR_T_DEFINED
typedef unsigned short wchar_t;
# define _WCHAR_T_DEFINED
# endif
# endif
// required for compatibility with glext.h sytle function definitions of
// OpenGL extensions, such as in src/osg/Point.cpp.
#ifndef APIENTRY
#define APIENTRY
#endif
#else
// Under windows avoid including <windows.h>
// to avoid name space pollution, but Win32's <GL/gl.h>
// needs APIENTRY and WINGDIAPI defined properly.
// F
# if 0
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
# else
// XXX This is from Win32's <windef.h>
# ifndef APIENTRY
# define GLUT_APIENTRY_DEFINED
# if (_MSC_VER >= 800) || defined(_STDCALL_SUPPORTED)
# define APIENTRY __stdcall
# else
# define APIENTRY
# endif
# endif
// XXX This is from Win32's <winnt.h>
# ifndef CALLBACK
# if (defined(_M_MRX000) || defined(_M_IX86) || defined(_M_ALPHA) || defined(_M_PPC)) && !defined(MIDL_PASS)
# define CALLBACK __stdcall
# else
# define CALLBACK
# endif
# endif
// XXX This is from Win32's <wingdi.h> and <winnt.h>
# ifndef WINGDIAPI
# define GLUT_WINGDIAPI_DEFINED
# define WINGDIAPI __declspec(dllimport)
# endif
// XXX This is from Win32's <ctype.h>
# ifndef _WCHAR_T_DEFINED
typedef unsigned short wchar_t;
# define _WCHAR_T_DEFINED
# endif
# endif
#ifndef __gl_h_
#include <GL/gl.h>
#endif
#ifndef __glu_h__
#include <GL/glu.h>
#endif
#else
// GL_GLEXT_LEGACY required by some Linux OpenGL implementations
// to allow compilation of glPointParameterfEXT.
#define GL_GLEXT_LEGACY 1
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glx.h>
#endif
#endif // __osgGL_h

View File

@@ -1,26 +1,21 @@
#ifndef OSG_GEOSET
#define OSG_GEOSET 1
#include <osg/OSG>
#include <osg/Vec2>
#include <osg/BoundingBox>
#include <osg/Object>
#include <osg/GeoState>
#include <osg/Vec3>
#include <osg/Vec4>
#include <osg/Drawable>
namespace osg {
class Input;
class Output;
/** Encapsulates OpenGL drawing primitives, geometry and
optional binding of normal, color and texture coordinates. Used
for representing the visible objects in the scene. State attributes
for a GeoSet are maintained in GeoState which the GeoSet maintains
a referenced counted pointer to. Both GeoSet's and GeoState's can
for a GeoSet are maintained in StateSet which the GeoSet maintains
a referenced counted pointer to. Both GeoSet's and StateSet's can
be shared for optimal memory usage and graphics performance.
*/
class SG_EXPORT GeoSet : public Object
class SG_EXPORT GeoSet : public Drawable
{
public:
@@ -67,201 +62,275 @@ class SG_EXPORT GeoSet : public Object
IA_T4F_C4F_N3F_V4F
};
struct IndexPointer
{
uint _size;
bool _is_ushort;
union
{
ushort* _ushort;
uint* _uint;
} _ptr;
IndexPointer() { _size=0;_is_ushort=true;_ptr._ushort = (ushort*)0; }
inline const bool operator == (const IndexPointer& ip) const
{
return _size == ip._size &&
_is_ushort == ip._is_ushort &&
_ptr._ushort == ip._ptr._ushort;
}
inline const bool valid() const
{
return _ptr._ushort != (ushort*)0;
}
inline const bool null() const
{
return _ptr._ushort == (ushort*)0;
}
inline void setToNull()
{
_size = 0;
_is_ushort = true;
_ptr._ushort = (ushort*)0;
}
inline void set(uint size,ushort* data)
{
_size = size;
_is_ushort = true;
_ptr._ushort = data;
}
void set(const uint size,uint* data)
{
_size = size;
_is_ushort = false;
_ptr._uint = data;
}
inline const uint maxIndex() const
{
uint max = 0;
if (_is_ushort)
{
for(uint ai = 0; ai < _size; ai++ )
if( _ptr._ushort[ai] > max ) max = _ptr._ushort[ai];
}
else
{
for(uint ai = 0; ai < _size; ai++ )
if( _ptr._uint[ai] > max ) max = _ptr._uint[ai];
}
return max;
}
inline const uint operator [] (const uint pos) const
{
if (_is_ushort) return _ptr._ushort[pos];
else return _ptr._uint[pos];
}
};
GeoSet();
static GeoSet* instance();
virtual Object* clone() const { return new GeoSet(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<GeoSet*>(obj)!=NULL; }
virtual const char* className() const { return "Geoset"; }
virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const GeoSet*>(obj)!=NULL; }
virtual const char* className() const { return "GeoSet"; }
// data access methods.
void setNumPrims( int n ) { _numprims = n; }
int getNumPrims( void ) { return _numprims; }
inline void setNumPrims( const int n ) { _numprims = n; }
inline const int getNumPrims() const { return _numprims; }
void setPrimType( PrimitiveType type );
PrimitiveType getPrimType( void ) { return _primtype; }
void setPrimType( const PrimitiveType type );
inline const PrimitiveType getPrimType() const { return _primtype; }
void setPrimLengths( int *lens ) { _primLengths = lens; }
int *getPrimLengths( void ) { return _primLengths; }
inline void setPrimLengths( int *lens ) { _primLengths = lens; }
inline int *getPrimLengths() { return _primLengths; }
inline const int *getPrimLengths() const { return _primLengths; }
void computeNumVerts();
/** get the number of coords required by the defined primitives. */
int getNumCoords() { return _numcoords; }
inline const int getNumCoords() const { return _numcoords; }
/** get a pointer to Vec3 coord array. */
Vec3* getCoords() { return _coords; }
inline Vec3* getCoords() { return _coords; }
/** get a const pointer to Vec3 coord array. */
inline const Vec3* getCoords() const { return _coords; }
/** get the number of indices required by the defined primitives. */
int getNumIndices() { return _numindices; }
inline const int getNumCoordIndices() const { return _cindex._size; }
/** get the coord index array. */
ushort* getCIndex() { return _cindex; }
inline IndexPointer& getCoordIndices() { return _cindex; }
/** get the const coord index array. */
inline const IndexPointer& getCoordIndices() const { return _cindex; }
/** set the coords (i.e the geometry) of the geoset.*/
void setCoords( Vec3 *cp );
/** set the coords (i.e the geometry) and indices of the geoset.*/
/** set the coords (i.e the geometry) and ushort indices of the geoset.
To reduce memory footprint and bandwidth for small datasets it is
recommended the ushort undices are used instead of unit indices.*/
void setCoords( Vec3 *cp, ushort *ci );
/** set the coords (i.e the geometry) and uint indices of the geoset.
Unless your data set exceeds 65536 indices prefer ushort indices
over uint indices, only use this unit indices version if neccessary.*/
void setCoords( Vec3 *cp, uint *ci );
/** set the coords (i.e the geometry) and indices of the geoset.*/
void setCoords( Vec3 *cp, IndexPointer& ip );
/** get the number of normals required by the defined primitives and normals binding.*/
int getNumNormals() { return _numnormals; }
inline const int getNumNormals() const { return _numnormals; }
/** get a pointer to Vec3 normal array. */
Vec3* getNormals() { return _normals; }
inline Vec3* getNormals() { return _normals; }
/** get a const pointer to Vec3 normal array. */
inline const Vec3* getNormals() const { return _normals; }
/** get the number of normal indices required by the defined primitives and normals binding.*/
int getNumNIndices() { return _numnindices; }
inline int getNumNormalIndices() const { return _nindex._size; }
/** get the normal index array. */
ushort* getNIndex() { return _nindex; }
inline IndexPointer& getNormalIndices() { return _nindex; }
/** get the const normal index array. */
inline const IndexPointer& getNormalIndices() const { return _nindex; }
/** set the normals of the geoset.*/
void setNormals( Vec3 *np );
/** set the normals and normal indices of the geoset.*/
void setNormals( Vec3 *np, ushort *ni );
/** set the normals and normal indices of the geoset.*/
void setNormals( Vec3 *np, uint *ni );
/** set the normals and normal indices of the geoset.*/
void setNormals( Vec3 *np, IndexPointer& ip );
/** set the normals binding to the vertices/primitives/overall.*/
void setNormalBinding( BindingType binding );
BindingType getNormalBinding() { return _normal_binding; }
void setNormalBinding( const BindingType binding );
inline const BindingType getNormalBinding() const { return _normal_binding; }
/** get the number of colors required by the defined primitives and color binding.*/
int getNumColors() { return _numcolors; }
inline const int getNumColors() const { return _numcolors; }
/** get a pointer to Vec4 color array. */
Vec4* getColors() { return _colors; }
inline Vec4* getColors() { return _colors; }
/** get a pointer to Vec4 color array. */
inline const Vec4* getColors() const { return _colors; }
/** get the number of colors indices required by the defined primitives and color binding.*/
int getNumCIndices() { return _numcindices; }
inline int getNumColorIndices() const { return _colindex._size; }
/** get the color index array. */
ushort* getColIndex() { return _colindex; }
inline IndexPointer& getColorIndices() { return _colindex; }
/** get the const color index array. */
inline const IndexPointer& getColorIndices() const { return _colindex; }
/** set the colors of the geoset.*/
void setColors( Vec4 *lp );
void setColors( Vec4 *cp );
/** set the colors and color indices of the geoset.*/
void setColors( Vec4 *lp, ushort *li );
void setColors( Vec4 *cp, ushort *li );
/** set the colors and color indices of the geoset.*/
void setColors( Vec4 *cp, uint *li );
/** set the colors and color indices of the geoset.*/
void setColors( Vec4 *cp, IndexPointer& ip );
/** set the color binding to the vertices/primitives/overall.*/
void setColorBinding( BindingType binding );
BindingType getColorBinding() { return _color_binding; }
inline BindingType getColorBinding() const { return _color_binding; }
/** get the number of texture coords required by the defined primitives and textures binding.*/
int getNumTCoords() { return _numtcoords; }
inline const int getNumTextureCoords() const { return _numtcoords; }
/** get a pointer to Vec4 color array. */
Vec2* getTCoords() { return _tcoords; }
inline Vec2* getTextureCoords() { return _tcoords; }
/** get a pointer to Vec4 color array. */
inline const Vec2* getTextureCoords() const { return _tcoords; }
/** get the number of texture coord indices required by the defined primitives and texture binding.*/
int getNumTIndices() { return _numtindices; }
inline const int getNumTextureIndices() const { return _tindex._size; }
/** get the texture index array. */
ushort* getTIndex() { return _tindex; }
inline IndexPointer& getTextureIndices() { return _tindex; }
/** get the texture index array. */
inline const IndexPointer& getTextureIndices() const { return _tindex; }
/** set the texture coords of the geoset.*/
void setTextureCoords( Vec2 *tc );
/** set the texture coords and texture coord indices of the geoset.*/
void setTextureCoords( Vec2 *tc, ushort *ti );
/** set the texture coords and texture coord indices of the geoset.*/
void setTextureCoords( Vec2 *tc, uint *ti );
/** set the texture coords and texture indices of the geoset.*/
void setTextureCoords( Vec2 *tc, IndexPointer& ip );
/** set the texture coord binding to the vertices/primitives/overall.*/
void setTextureBinding( BindingType binding );
BindingType getTextureBinding() { return _texture_binding; }
void setInterleavedArray( InterleaveArrayType format, float *ia );
void setInterleavedArray( InterleaveArrayType format, float *ia, ushort *iai );
void setGeoState(GeoState *state) { _state = state; }
GeoState* getGeoState() const { return _state.get();}
/** When set to true, force the draw method to use OpenGL Display List for rendering.
If false rendering directly. If the display list has not been already
compile the next call to draw will automatically create the display list.*/
void setUseDisplayList(bool flag);
/** Return whether OpenGL display lists are being used for rendering.*/
bool getUseDisplayList() { return _useDisplayList; }
/** Force a recompile on next draw() of any OpenGL display list associated with this geoset.*/
void dirtyDisplayList();
/** get bounding box of geoset.
* Note, now made virtual to make it possible to implement user-drawn
* objects albiet so what crudely, to be improved later.
*/
virtual const BoundingBox& getBound() ;
/** draw geoset.
* If the geoset has _useDisplayList set to true then use an OpenGL display
* list, automatically compiling one if required.
* Otherwise call drawImmediateMode().
* Note, draw method should not be overiden in subclasses as it
* manages the optional display list.
*/
void draw( void );
void setTextureBinding( const BindingType binding );
inline const BindingType getTextureBinding() const { return _texture_binding; }
/** get the number of texture coords required by the defined primitives and textures binding.*/
inline const int getNumInterleavedCoords() const { return _numcoords; }
/** get a pointer to interleaved float array. */
inline void* getInterleavedArray() { return _iarray; }
/** get a const pointer to interleaved float array. */
inline const void* getInterleavedArray() const { return _iarray; }
/** get the number of texture coord indices required by the defined primitives and texture binding.*/
inline const int getNumIterleavedIndices() const { return _iaindex._size; }
/** get the texture index array. */
inline IndexPointer& getInterleavedIndices() { return _iaindex; }
/** get the interleaved index array. */
inline const IndexPointer& getInterleavedIndices() const { return _iaindex; }
/** get the interleaved array storage format. */
inline const InterleaveArrayType getInterleavedFromat() const { return _iaformat; }
/** set the interleaved arrays of the geoset.*/
void setInterleavedArray( const InterleaveArrayType format, float *ia );
void setInterleavedArray( const InterleaveArrayType format, float *ia, ushort *iai );
void setInterleavedArray( const InterleaveArrayType format, float *ia, uint *iai );
void setInterleavedArray( const InterleaveArrayType format, float *ia, IndexPointer& iai );
/** draw geoset directly ignoring an OpenGL display list which could be attached.
* This is the internal draw method which does the drawing itself,
* and is the method to override when deriving from GeoSet for user-drawn objects.
*/
virtual void drawImmediateMode();
virtual void drawImmediateMode(State& state);
/** Immediately compile this geoset into an OpenGL Display List, set _useDisplayList to true.*/
void compile( void );
bool check();
const bool check() const;
protected:
GeoSet(const GeoSet&):Object() {}
GeoSet(const GeoSet&):Drawable() {}
GeoSet& operator = (const GeoSet&) { return *this;}
virtual ~GeoSet();
bool matchBindingTypeStr(const char* str,BindingType& mode);
const char* getBindingTypeStr(BindingType mode);
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
private :
virtual const bool computeBound() const;
int _numprims;
PrimitiveType _primtype;
int _needprimlen;
unsigned int _oglprimtype;
int *_primLengths;
int _numverts;
unsigned char _primlength;
unsigned char _flat_shaded_skip;
int _numcoords;
int _numindices;
Vec3 *_coords;
ushort *_cindex;
int _numcoords;
Vec3 *_coords;
IndexPointer _cindex;
int _numnormals;
int _numnindices;
Vec3 *_normals;
ushort *_nindex;
BindingType _normal_binding;
BindingType _normal_binding;
int _numnormals;
Vec3 *_normals;
IndexPointer _nindex;
int _numcolors;
int _numcindices;
Vec4 *_colors;
ushort *_colindex;
BindingType _color_binding;
BindingType _color_binding;
int _numcolors;
Vec4 *_colors;
IndexPointer _colindex;
int _numtcoords;
int _numtindices;
Vec2 *_tcoords;
ushort *_tindex;
BindingType _texture_binding;
BindingType _texture_binding;
int _numtcoords;
Vec2 *_tcoords;
IndexPointer _tindex;
void *_iarray;
ushort *_iaindex;
void *_iarray;
IndexPointer _iaindex;
InterleaveArrayType _iaformat;
unsigned int _ogliaformat;
/** return the bbbbffff composition required for an interleaved array row.*/
const char* getInterleavedRowComposition(InterleaveArrayType at) const;
/** return the number of bytes required for an interleaved array row.*/
int getInterleavedRowLength(InterleaveArrayType at) const;
int _fast_path;
ref_ptr<GeoState> _state;
bool _useDisplayList;
uint _globj;
BoundingBox _bbox;
int _bbox_computed;
void computeBound( void );
void set_fast_path( void );
void draw_fast_path( void );
void draw_alternate_path( void );
@@ -279,21 +348,47 @@ void for_each_triangle(GeoSet& gset,T& op)
case(GeoSet::TRIANGLE_STRIP):
case(GeoSet::FLAT_TRIANGLE_STRIP):
{
if (gset.getCIndex())
if (gset.getCoordIndices().valid())
{
ushort* iptr = gset.getCIndex();
Vec3* vptr = gset.getCoords();
const int numPrim = gset.getNumPrims();
for(int i=0; i<numPrim; ++i )
if (gset.getCoordIndices()._is_ushort)
{
const int primLength = gset.getPrimLengths()[i];
ushort* iend = iptr+primLength;
for(int j = 2; j < primLength; j++ )
ushort* iptr = gset.getCoordIndices()._ptr._ushort;
Vec3* vptr = gset.getCoords();
const int numPrim = gset.getNumPrims();
for(int i=0; i<numPrim; ++i )
{
op(vptr[*(iptr)],vptr[*(iptr+1)],vptr[*(iptr+2)]);
++iptr;
const int primLength = gset.getPrimLengths()[i];
ushort* iend = iptr+primLength;
for(int j = 2; j < primLength; j++ )
{
if( !(j%2) )
op(vptr[*(iptr)],vptr[*(iptr+1)],vptr[*(iptr+2)]);
else
op(vptr[*(iptr)],vptr[*(iptr+2)],vptr[*(iptr+1)]);
++iptr;
}
iptr=iend;
}
}
else
{
uint* iptr = gset.getCoordIndices()._ptr._uint;
Vec3* vptr = gset.getCoords();
const int numPrim = gset.getNumPrims();
for(int i=0; i<numPrim; ++i )
{
const int primLength = gset.getPrimLengths()[i];
uint* iend = iptr+primLength;
for(int j = 2; j < primLength; j++ )
{
if( !(j%2) )
op(vptr[*(iptr)],vptr[*(iptr+1)],vptr[*(iptr+2)]);
else
op(vptr[*(iptr)],vptr[*(iptr+2)],vptr[*(iptr+1)]);
++iptr;
}
iptr=iend;
}
iptr=iend;
}
}
else
@@ -306,7 +401,10 @@ void for_each_triangle(GeoSet& gset,T& op)
Vec3* vend = vptr+primLength;
for(int j = 2; j < primLength; j++ )
{
op(*(vptr),*(vptr+1),*(vptr+2));
if( !(j%2) )
op(*(vptr),*(vptr+1),*(vptr+2));
else
op(*(vptr),*(vptr+2),*(vptr+1));
++vptr;
}
vptr=vend;
@@ -317,15 +415,29 @@ void for_each_triangle(GeoSet& gset,T& op)
case(GeoSet::TRIANGLES):
{
if (gset.getCIndex())
if (gset.getCoordIndices().valid())
{
ushort* iptr = gset.getCIndex();
Vec3* vptr = gset.getCoords();
const int numPrim = gset.getNumPrims();
for(int i=0; i<numPrim; ++i )
if (gset.getCoordIndices()._is_ushort)
{
op(vptr[*(iptr)],vptr[*(iptr+1)],vptr[*(iptr+2)]);
iptr+=3;
ushort* iptr = gset.getCoordIndices()._ptr._ushort;
Vec3* vptr = gset.getCoords();
const int numPrim = gset.getNumPrims();
for(int i=0; i<numPrim; ++i )
{
op(vptr[*(iptr)],vptr[*(iptr+1)],vptr[*(iptr+2)]);
iptr+=3;
}
}
else
{
uint* iptr = gset.getCoordIndices()._ptr._uint;
Vec3* vptr = gset.getCoords();
const int numPrim = gset.getNumPrims();
for(int i=0; i<numPrim; ++i )
{
op(vptr[*(iptr)],vptr[*(iptr+1)],vptr[*(iptr+2)]);
iptr+=3;
}
}
}
else
@@ -343,22 +455,43 @@ void for_each_triangle(GeoSet& gset,T& op)
break;
case(GeoSet::QUAD_STRIP):
{
if (gset.getCIndex())
if (gset.getCoordIndices().valid())
{
ushort* iptr = gset.getCIndex();
Vec3* vptr = gset.getCoords();
const int numPrim = gset.getNumPrims();
for(int i=0; i<numPrim; ++i )
if (gset.getCoordIndices()._is_ushort)
{
const int primLength = gset.getPrimLengths()[i];
ushort* iend = iptr+primLength;
for(int j = 3; j < primLength; j+=2 )
ushort* iptr = gset.getCoordIndices()._ptr._ushort;
Vec3* vptr = gset.getCoords();
const int numPrim = gset.getNumPrims();
for(int i=0; i<numPrim; ++i )
{
op(vptr[*(iptr)],vptr[*(iptr+1)],vptr[*(iptr+2)]);
op(vptr[*(iptr)],vptr[*(iptr+3)],vptr[*(iptr+2)]);
iptr+=2;
const int primLength = gset.getPrimLengths()[i];
ushort* iend = iptr+primLength;
for(int j = 3; j < primLength; j+=2 )
{
op(vptr[*(iptr)],vptr[*(iptr+1)],vptr[*(iptr+2)]);
op(vptr[*(iptr)],vptr[*(iptr+3)],vptr[*(iptr+2)]);
iptr+=2;
}
iptr=iend;
}
}
else
{
uint* iptr = gset.getCoordIndices()._ptr._uint;
Vec3* vptr = gset.getCoords();
const int numPrim = gset.getNumPrims();
for(int i=0; i<numPrim; ++i )
{
const int primLength = gset.getPrimLengths()[i];
uint* iend = iptr+primLength;
for(int j = 3; j < primLength; j+=2 )
{
op(vptr[*(iptr)],vptr[*(iptr+1)],vptr[*(iptr+2)]);
op(vptr[*(iptr)],vptr[*(iptr+3)],vptr[*(iptr+2)]);
iptr+=2;
}
iptr=iend;
}
iptr=iend;
}
}
else
@@ -382,16 +515,31 @@ void for_each_triangle(GeoSet& gset,T& op)
break;
case(GeoSet::QUADS):
{
if (gset.getCIndex())
if (gset.getCoordIndices().valid())
{
ushort* iptr = gset.getCIndex();
Vec3* vptr = gset.getCoords();
const int numPrim = gset.getNumPrims();
for(int i=0; i<numPrim; ++i )
if (gset.getCoordIndices()._is_ushort)
{
op(vptr[*(iptr)],vptr[*(iptr+1)],vptr[*(iptr+2)]);
op(vptr[*(iptr)],vptr[*(iptr+3)],vptr[*(iptr+2)]);
iptr+=4;
ushort* iptr = gset.getCoordIndices()._ptr._ushort;
Vec3* vptr = gset.getCoords();
const int numPrim = gset.getNumPrims();
for(int i=0; i<numPrim; ++i )
{
op(vptr[*(iptr)],vptr[*(iptr+1)],vptr[*(iptr+2)]);
op(vptr[*(iptr)],vptr[*(iptr+3)],vptr[*(iptr+2)]);
iptr+=4;
}
}
else
{
uint* iptr = gset.getCoordIndices()._ptr._uint;
Vec3* vptr = gset.getCoords();
const int numPrim = gset.getNumPrims();
for(int i=0; i<numPrim; ++i )
{
op(vptr[*(iptr)],vptr[*(iptr+1)],vptr[*(iptr+2)]);
op(vptr[*(iptr)],vptr[*(iptr+3)],vptr[*(iptr+2)]);
iptr+=4;
}
}
}
else
@@ -411,25 +559,50 @@ void for_each_triangle(GeoSet& gset,T& op)
case(GeoSet::TRIANGLE_FAN):
case(GeoSet::POLYGON):
{
if (gset.getCIndex())
if (gset.getCoordIndices().valid())
{
ushort* iptr = gset.getCIndex();
Vec3* vptr = gset.getCoords();
const int numPrim = gset.getNumPrims();
for(int i=0; i<numPrim; ++i )
if (gset.getCoordIndices()._is_ushort)
{
const int primLength = gset.getPrimLengths()[i];
if (primLength>0)
ushort* iptr = gset.getCoordIndices()._ptr._ushort;
Vec3* vptr = gset.getCoords();
const int numPrim = gset.getNumPrims();
for(int i=0; i<numPrim; ++i )
{
const Vec3& start = vptr[*(iptr)];
ushort* iend = iptr+primLength;
++iptr;
for(int j = 2; j < primLength; ++j )
const int primLength = gset.getPrimLengths()[i];
if (primLength>0)
{
op(start,vptr[*(iptr)],vptr[*(iptr+1)]);
const Vec3& start = vptr[*(iptr)];
ushort* iend = iptr+primLength;
++iptr;
for(int j = 2; j < primLength; ++j )
{
op(start,vptr[*(iptr)],vptr[*(iptr+1)]);
++iptr;
}
iptr=iend;
}
}
}
else
{
uint* iptr = gset.getCoordIndices()._ptr._uint;
Vec3* vptr = gset.getCoords();
const int numPrim = gset.getNumPrims();
for(int i=0; i<numPrim; ++i )
{
const int primLength = gset.getPrimLengths()[i];
if (primLength>0)
{
const Vec3& start = vptr[*(iptr)];
uint* iend = iptr+primLength;
++iptr;
for(int j = 2; j < primLength; ++j )
{
op(start,vptr[*(iptr)],vptr[*(iptr+1)]);
++iptr;
}
iptr=iend;
}
iptr=iend;
}
}
}

View File

@@ -1,70 +1,69 @@
#ifndef OSG_GEODE
#define OSG_GEODE 1
#include <osg/OSG>
#include <osg/Node>
#include <osg/GeoSet>
#include <osg/NodeVisitor>
#include <vector>
#include <osg/Drawable>
namespace osg {
/** Leaf Node for grouping GeoSets.*/
/** Leaf Node for grouping Drawables.*/
class SG_EXPORT Geode : public Node
{
public:
typedef std::vector< ref_ptr<GeoSet> > GeoSetList;
typedef std::vector< ref_ptr<Drawable> > DrawableList;
Geode();
virtual Object* clone() const { return new Geode(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<Geode*>(obj)!=NULL; }
virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const Geode*>(obj)!=NULL; }
virtual const char* className() const { return "Geode"; }
virtual void accept(NodeVisitor& nv) { nv.apply(*this); }
/** Add GeoSet to Geode.
/** Add Drawable to Geode.
* If gset is not NULL and is not contained in Geode then increment its
* reference count, add it to the geosets list and dirty the bounding
* reference count, add it to the drawables list and dirty the bounding
* sphere to force it to recompute on next getBound() and return true for success.
* Otherwise return false.
*/
virtual bool addGeoSet( GeoSet *gset );
virtual const bool addDrawable( Drawable *drawable );
/** Remove GeoSet from Geode.
/** Remove Drawable from Geode.
* If gset is contained in Geode then remove it from the geoset
* list and decrement its reference count, and dirty the
* bounding sphere to force it to recompute on next getBound() and
* return true for success. If gset is not found then return false
* and do not change the reference count of gset.
*/
virtual bool removeGeoSet( GeoSet *gset );
virtual const bool removeDrawable( Drawable *drawable );
/** Replace specified GeoSet with another GeoSet.
/** Replace specified Drawable with another Drawable.
* Decrement the reference count origGSet and increments the
* reference count of newGset, and dirty the bounding sphere
* to force it to recompute on next getBound() and returns true.
* If origGeoSet is not found then return false and do not
* If origDrawable is not found then return false and do not
* add newGset. If newGset is NULL then return false and do
* not remove origGset.
*/
virtual bool replaceGeoSet( GeoSet *origGset, GeoSet *newGset );
virtual const bool replaceDrawable( Drawable *origDraw, Drawable *newDraw );
/** return the number of geoset's.*/
int getNumGeosets( void ) const { return _geosets.size(); }
inline const int getNumDrawables() const { return _drawables.size(); }
/** return geoset at position i.*/
GeoSet* getGeoSet( int i ) { return _geosets[i].get(); }
inline Drawable* getDrawable( const int i ) { return _drawables[i].get(); }
/** return geoset at position i.*/
inline const Drawable* getDrawable( const int i ) const { return _drawables[i].get(); }
/** return true is geoset is contained within Geode.*/
bool containsGeoSet( GeoSet* gset)
inline const bool containsDrawable(const Drawable* gset) const
{
for (GeoSetList::iterator itr=_geosets.begin();
itr!=_geosets.end();
for (DrawableList::const_iterator itr=_drawables.begin();
itr!=_drawables.end();
++itr)
{
if (itr->get()==gset) return true;
@@ -72,34 +71,46 @@ class SG_EXPORT Geode : public Node
return false;
}
/** return the iterator postion for specified GeoSet.
/** return the iterator postion for specified Drawable.
* return _geoset.end() if gset not is contained in Geode.
*/
GeoSetList::iterator findGeoSet( GeoSet* gset)
inline DrawableList::iterator findDrawable(const Drawable* gset)
{
for (GeoSetList::iterator itr=_geosets.begin();
itr!=_geosets.end();
for (DrawableList::iterator itr=_drawables.begin();
itr!=_drawables.end();
++itr)
{
if (itr->get()==gset) return itr;
}
return _geosets.end();
return _drawables.end();
}
/** return the const_iterator postion for specified Drawable.
* return _geoset.end() if gset not is contained in Geode.
*/
inline DrawableList::const_iterator findDrawable(const Drawable* gset) const
{
for (DrawableList::const_iterator itr=_drawables.begin();
itr!=_drawables.end();
++itr)
{
if (itr->get()==gset) return itr;
}
return _drawables.end();
}
/** complile OpenGL Display List for each geoset.*/
void compileGeoSets( void );
void compileDrawables(State& state);
protected:
virtual ~Geode();
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
virtual const bool computeBound() const;
virtual bool computeBound( void );
GeoSetList _geosets;
DrawableList _drawables;
};

View File

@@ -4,12 +4,10 @@
#include <osg/Node>
#include <osg/NodeVisitor>
#include <vector>
namespace osg {
/** General group node which maintains a list of children.
Children are reference counted to allow children to be shared
Children are reference counted. This allows children to be shared
with memory management handled automatically via osg::Referenced.
*/
class SG_EXPORT Group : public Node
@@ -21,7 +19,7 @@ class SG_EXPORT Group : public Node
Group();
virtual Object* clone() const { return new Group(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<Group*>(obj)!=NULL; }
virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const Group*>(obj)!=NULL; }
virtual const char* className() const { return "Group"; }
virtual void accept(NodeVisitor& nv) { nv.apply(*this); }
@@ -31,7 +29,7 @@ class SG_EXPORT Group : public Node
* If node is not NULL and is not contained in Group then increment its
* reference count, add it to the child list and dirty the bounding
* sphere to force it to recompute on next getBound() and return true for success.
* Otherwise return false.
* Otherwise return false. Scene nodes can't be added as child nodes.
*/
virtual bool addChild( Node *child );
@@ -50,21 +48,24 @@ class SG_EXPORT Group : public Node
* to force it to recompute on next getBound() and returns true.
* If origNode is not found then return false and do not
* add newNode. If newNode is NULL then return false and do
* not remove origNode.
* not remove origNode. Also returns false if newChild is a Scene node.
*/
virtual bool replaceChild( Node *origChild, Node* newChild );
/** return the number of chilren nodes.*/
int getNumChildren( void ) { return _children.size(); }
inline const int getNumChildren() const { return _children.size(); }
/** return child node at position i.*/
Node *getChild( int i ) { return _children[i].get(); }
inline Node *getChild( const int i ) { return _children[i].get(); }
/** return true is node is contained within Group.*/
bool containsNode( Node* node )
/** return child node at position i.*/
inline const Node *getChild( const int i ) const { return _children[i].get(); }
/** return true if node is contained within Group.*/
inline bool containsNode( const Node* node ) const
{
for (ChildList::iterator itr=_children.begin();
for (ChildList::const_iterator itr=_children.begin();
itr!=_children.end();
++itr)
{
@@ -73,12 +74,12 @@ class SG_EXPORT Group : public Node
return false;
}
/** return the iterator postion for specified Node.
* return _chilren.end() if node is not contained in Group.
*/
ChildList::iterator findNode( Node* node )
inline ChildList::iterator findNode( const Node* node )
{
for (ChildList::iterator itr=_children.begin();
itr!=_children.end();
++itr)
@@ -88,16 +89,28 @@ class SG_EXPORT Group : public Node
return _children.end();
}
/** return the const_iterator postion for specified Node.
* return _chilren.end() if node is not contained in Group.
*/
inline ChildList::const_iterator findNode( const Node* node ) const
{
for (ChildList::const_iterator itr=_children.begin();
itr!=_children.end();
++itr)
{
if (itr->get()==node) return itr;
}
return _children.end();
}
protected:
virtual ~Group();
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
virtual const bool computeBound() const;
ChildList _children;
bool computeBound( void );
};

View File

@@ -1,14 +1,14 @@
// -*-c++-*-
#ifndef OSG_IMAGE
#define OSG_IMAGE 1
#include <osg/Object>
#include <osg/OSG>
#include <string>
namespace osg {
class Output;
class Input;
/** Image class for encapsulating the storage texture image data.*/
class SG_EXPORT Image : public Object
{
@@ -18,50 +18,56 @@ class SG_EXPORT Image : public Object
Image();
virtual Object* clone() const { return new Image(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<Image*>(obj)!=NULL; }
virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const Image*>(obj)!=0; }
virtual const char* className() const { return "Image"; }
const char* getFileName() { return _fileName; }
void setFileName(const char* fileName);
inline const std::string& getFileName() const { return _fileName; }
void setFileName(const std::string& fileName);
/** set the image data and format.
* note, when no packing value is negative (the default is -1) this method assumes
* note, when the packing value is negative (the default is -1) this method assumes
* a _packing width of 1 if the width is not a multiple of 4,
* otherwise automatically sets to _packing to 4. If a postive
* value of packing is supplied than _packing is simply set to that value.
*/
void setImage(int s,int t,int r,
int internalFormat,
unsigned int pixelFormat,
unsigned int dataType,
void setImage(const int s,const int t,const int r,
const int internalFormat,
const unsigned int pixelFormat,
const unsigned int dataType,
unsigned char *data,
int packing=-1);
const int packing=-1);
/** Width of image.*/
int s() { return _s; }
inline const int s() const { return _s; }
/** Height of image.*/
int t() { return _t; }
inline const int t() const { return _t; }
/** Depth of image.*/
int r() { return _r; }
inline const int r() const { return _r; }
int internalFormat() { return _internalFormat; }
unsigned int pixelFormat() { return _pixelFormat; }
unsigned int dataType() { return _dataType; }
unsigned int packing() { return _packing; }
inline const int internalFormat() const { return _internalFormat; }
inline const unsigned int pixelFormat() const { return _pixelFormat; }
inline const unsigned int dataType() const { return _dataType; }
inline const unsigned int packing() const { return _packing; }
/** raw image data.*/
unsigned char *data() { return _data; }
inline unsigned char *data() { return _data; }
/** raw const image data.*/
inline const unsigned char *data() const { return _data; }
/** Scale image to specified size. */
void scaleImage(int s,int t,int r);
void scaleImage(const int s,const int t,const int r);
/** Ensure image dimensions are a power of two.
* Mip Mapped texture require the image dimensions to be
* power of two.
*/
void ensureDimensionsArePowerOfTwo();
/** Get modified tag value. */
inline const unsigned int getModifiedTag() const { return _modifiedTag; }
protected :
virtual ~Image();
@@ -69,10 +75,7 @@ class SG_EXPORT Image : public Object
// Image(const Image&) {}
// Image& operator = (const Image& image) {}
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
char* _fileName;
std::string _fileName;
int _s, _t, _r;
int _internalFormat;
unsigned int _pixelFormat;
@@ -80,18 +83,21 @@ class SG_EXPORT Image : public Object
unsigned int _packing;
unsigned char *_data;
unsigned int _modifiedTag;
};
class Geode;
/** Convinience function to be used by images loaders to generate a valid geode to return for readNode().
* Use the images s and t values scale the dimensions of the image.
*/
/** Convenience function to be used by images loaders to generate a valid geode
* to return for readNode().
* Use the images s and t values scale the dimensions of the image.
*/
SG_EXPORT extern Geode* createGeodeForImage(Image* image);
/** Convinience function to be used by images loaders to generate a valid geode to return for readNode().
* Use the specified s and t values scale the dimensions of the image.
*/
SG_EXPORT extern Geode* createGeodeForImage(Image* image,float s,float t);
/** Convenience function to be used by images loaders to generate a valid geode
* to return for readNode().
* Use the specified s and t values scale the dimensions of the image.
*/
SG_EXPORT extern Geode* createGeodeForImage(Image* image,const float s,const float t);
};

View File

@@ -1,9 +1,7 @@
#ifndef OSG_LOD
#define OSG_LOD 1
#include <osg/Switch>
#include <vector>
#include <osg/Group>
namespace osg {
@@ -20,7 +18,7 @@ class SG_EXPORT LOD : public Group
LOD() {}
virtual Object* clone() const { return new LOD(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<LOD*>(obj)!=NULL; }
virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const LOD*>(obj)!=NULL; }
virtual const char* className() const { return "LOD"; }
virtual void accept(NodeVisitor& nv) { nv.apply(*this); }
virtual void traverse(NodeVisitor& nv);
@@ -29,31 +27,31 @@ class SG_EXPORT LOD : public Group
is a floating point distance specified in world coordinates.
Range list automatically expands to accomodate values beyond
the current getNumRanges().*/
void setRange(unsigned int index, float range);
/** pfLOD::getRange returns the range element index.*/
float getRange(unsigned int index) { return _rangeList[index]; }
void setRange(const unsigned int index, const float range);
/** returns the range for specified index.*/
inline const float getRange(const unsigned int index) const { return _rangeList[index]; }
/** returns the number of ranges currently set.*/
int getNumRanges() { return _rangeList.size(); }
inline const int getNumRanges() const { return _rangeList.size(); }
/** Sets the object-space point which defines the center of the osg::LOD.
center is affected by any transforms in the hierarchy above the osg::LOD.*/
void setCenter(const Vec3 &center) { _center = center; }
inline void setCenter(const Vec3 &center) { _center = center; }
/** return the LOD center point. */
const Vec3& getCenter() { return _center; }
inline const Vec3& getCenter() const { return _center; }
/** return the child to traverse.
Selected by the distance between the eye point in local
coordinates and the LOD center, mutliplied by the bias.*/
int evaluate(const Vec3& eye_local,float bias=1.0f);
const int evaluate(const Vec3& eye_local,const float bias=1.0f) const;
protected :
virtual ~LOD() {}
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
typedef std::vector<float> RangeList;
RangeList _rangeList;
RangeList _rangeList2;

View File

@@ -1,113 +1,111 @@
#ifndef OSG_LIGHT
#define OSG_LIGHT 1
#include <osg/GL>
#include <osg/OSG>
#include <osg/Vec3>
#include <osg/Vec4>
#include <osg/StateAttribute>
#include <osg/StateSet>
namespace osg {
/** Light state class which encapsulates OpenGL glLight() functionality.*/
class SG_EXPORT Light : public Object
class SG_EXPORT Light : public StateAttribute
{
public :
Light();
/** return a static instance of an osg::Light, to be used as prototype
for loading lights.*/
static Light* instance();
/** return a shallow copy of a node, with Object* return type.*/
virtual Object* clone() const { return new Light(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<Light*>(obj)!=NULL; }
/** return true if this and obj are of the same kind of object.*/
virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const Light*>(obj)!=NULL; }
/** return the name of the node's class type.*/
virtual const char* className() const { return "Light"; }
virtual const Type getType() const { return LIGHTING; }
virtual void setStateSetModes(StateSet& ds,const GLModeValue value) const
{
ds.setMode((GLMode)(GL_LIGHT0+_lightnum),value);
}
/**
* Turn the light on.
* Calling this method doesn't directly affect OpenGL's lighting mode.
*/
void on( void ) { _on = true; }
inline void on() { _on = true; }
/**
* Turn the light off.
* Calling this method doesn't directly affect OpenGL's lighting mode.
*/
void off( void ) { _on = false; }
/** Enable OpenGL's Lighting mode. */
static void enable( void );
/** Disable OpenGL's Lighting mode. */
static void disable( void );
inline void off() { _on = false; }
/** Apply the light's state to the OpenGL state machine. */
void apply( void );
virtual void apply(State& state) const;
/** Set the ambient component of the light. */
void setAmbient( const Vec4& ambient ) { _ambient = ambient; }
inline void setAmbient( const Vec4& ambient ) { _ambient = ambient; }
/** Get the ambient component of the light. */
const Vec4& getAmbient() const { return _ambient; }
inline const Vec4& getAmbient() const { return _ambient; }
/** Set the diffuse component of the light. */
void setDiffuse( const Vec4& diffuse ) { _diffuse = diffuse; }
inline void setDiffuse( const Vec4& diffuse ) { _diffuse = diffuse; }
/** Get the diffuse component of the light. */
const Vec4& getDiffuse() const { return _diffuse; }
inline const Vec4& getDiffuse() const { return _diffuse; }
/** Set the specular component of the light. */
void setSpecular( const Vec4& specular ) { _specular = specular; }
inline void setSpecular( const Vec4& specular ) { _specular = specular; }
/** Get the specular component of the light. */
const Vec4& getSpecular() const { return _specular; }
inline const Vec4& getSpecular() const { return _specular; }
/** Set the position of the light. */
void setPosition( const Vec4& position ) { _position = position; }
inline void setPosition( const Vec4& position ) { _position = position; }
/** Get the position of the light. */
const Vec4& getPosition() const { return _position; }
inline const Vec4& getPosition() const { return _position; }
/** Set the direction of the light. */
void setDirection( const Vec3& direction ) { _direction = direction; }
inline void setDirection( const Vec3& direction ) { _direction = direction; }
/** Get the direction of the light. */
const Vec3& getDirection() const { return _direction; }
inline const Vec3& getDirection() const { return _direction; }
/** Set the constant attenuation of the light. */
void setConstantAttenuation( float constant_attenuation ) { _constant_attenuation = constant_attenuation; }
inline void setConstantAttenuation( const float constant_attenuation ) { _constant_attenuation = constant_attenuation; }
/** Get the constant attenuation of the light. */
float setConstantAttenuation() const { return _constant_attenuation; }
inline const float getConstantAttenuation() const { return _constant_attenuation; }
/** Set the linear attenuation of the light. */
void setLinearAttenuation ( float linear_attenuation ) { _linear_attenuation = linear_attenuation; }
inline void setLinearAttenuation ( const float linear_attenuation ) { _linear_attenuation = linear_attenuation; }
/** Get the linear attenuation of the light. */
float getLinearAttenuation () const { return _linear_attenuation; }
inline const float getLinearAttenuation () const { return _linear_attenuation; }
/** Set the quadratic attenuation of the light. */
void setQuadraticAttenuation ( float quadratic_attenuation ) { _quadratic_attenuation = quadratic_attenuation; }
inline void setQuadraticAttenuation ( const float quadratic_attenuation ) { _quadratic_attenuation = quadratic_attenuation; }
/** Get the quadratic attenuation of the light. */
float getQuadraticAttenuation() const { return _quadratic_attenuation; }
inline const float getQuadraticAttenuation() const { return _quadratic_attenuation; }
/** Set the spot exponent of the light. */
void setSpotExponent( float spot_exponent ) { _spot_exponent = spot_exponent; }
inline void setSpotExponent( const float spot_exponent ) { _spot_exponent = spot_exponent; }
/** Get the spot exponent of the light. */
float getSpotExponent() const { return _spot_exponent; }
inline const float getSpotExponent() const { return _spot_exponent; }
/** Set the spot cutoff of the light. */
void setSpotCutoff( float spot_cutoff ) { _spot_cutoff = spot_cutoff; }
inline void setSpotCutoff( const float spot_cutoff ) { _spot_cutoff = spot_cutoff; }
/** Get the spot cutoff of the light. */
float getSpotCutoff() { return _spot_cutoff; }
inline const float getSpotCutoff() const { return _spot_cutoff; }
/**
* Capture the lighting settings of the current OpenGL state
@@ -117,10 +115,10 @@ class SG_EXPORT Light : public Object
protected :
virtual ~Light( void );
virtual ~Light();
/** Initialize the light's settings with some decent defaults. */
void init( void );
void init();
int _lightnum; // OpenGL light number
bool _on; // on/off state

View File

@@ -1,7 +1,7 @@
#ifndef OSG_LIGHTSOURCE
#define OSG_LIGHTSOURCE 1
#include <osg/Node>
#include <osg/MemoryAdapter>
#include <osg/NodeVisitor>
#include <osg/Light>
@@ -15,24 +15,24 @@ class SG_EXPORT LightSource : public Node
LightSource();
virtual Object* clone() const { return new LightSource(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<LightSource*>(obj)!=NULL; }
virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const LightSource*>(obj)!=NULL; }
virtual const char* className() const { return "LightSource"; }
virtual void accept(NodeVisitor& nv) { nv.apply(*this); }
/** Set the attached light.*/
void setLight(Light* light) { _light = light; }
inline void setLight(Light* light) { _light = light; }
/** Get the attached light.*/
Light* getLight() { return _light.get(); }
inline Light* getLight() { return _light.get(); }
/** Get the const attached light.*/
inline const Light* getLight() const { return _light.get(); }
protected:
virtual ~LightSource();
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
virtual bool computeBound( void );
virtual const bool computeBound() const;
ref_ptr<Light> _light;
};

View File

@@ -1,26 +1,39 @@
#ifndef OSG_MATERIAL
#define OSG_MATERIAL 1
#include <osg/GL>
#include <osg/OSG>
#include <osg/Vec4>
#include <osg/Object>
#include <osg/StateAttribute>
#include <osg/StateSet>
namespace osg {
class Input;
class Output;
class SG_EXPORT Material : public Object
/** Material - encapsulates OpenGL glMaterial state.*/
class SG_EXPORT Material : public StateAttribute
{
public :
enum MaterialFace {
FACE_FRONT = GL_FRONT,
FACE_BACK = GL_BACK,
FACE_FRONT_AND_BACK = GL_FRONT_AND_BACK
Material();
virtual Object* clone() const { return new Material(); }
virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const Material*>(obj)!=NULL; }
const char* className() const { return "Material"; }
virtual const Type getType() const { return MATERIAL; }
virtual void setStateSetModes(StateSet& ds,const GLModeValue value) const
{
// Have to think about the role of _colorMode
// in setting the colormaterial... also need to take the
// color material enable/disable out of the the apply()...
ds.setMode(GL_COLOR_MATERIAL,value);
}
virtual void apply(State& state) const;
enum Face {
FRONT = GL_FRONT,
BACK = GL_BACK,
FRONT_AND_BACK = GL_FRONT_AND_BACK
};
enum ColorMode {
@@ -32,44 +45,51 @@ class SG_EXPORT Material : public Object
OFF
};
Material( void );
static Material* instance();
virtual Object* clone() const { return new Material(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<Material*>(obj)!=NULL; }
const char* className() const { return "Material"; }
inline void setColorMode(const ColorMode mode) { _colorMode = mode; }
inline const ColorMode getColorMode() const { return _colorMode; }
void apply( void );
void setAmbient( const Face face, const Vec4& ambient );
const Vec4& getAmbient(const Face face) const;
inline const bool getAmbientFrontAndBack() const { return _ambientFrontAndBack; }
void setColorMode(ColorMode mode) { _colorMode = mode; }
void setDiffuse( const Face face, const Vec4& diffuse );
const Vec4& getDiffuse(const Face face) const;
inline const bool getDiffuseFrontAndBack() const { return _diffuseFrontAndBack; }
void setAmbient( MaterialFace face, const Vec4& ambient );
const Vec4& getAmbient(MaterialFace face) const;
bool getAmbientFrontAndBack() { return _ambientFrontAndBack; }
/** Set specular value of specified face(s) of the material,
* valid specular[0..3] range is 0.0 to 1.0.*/
void setSpecular( const Face face, const Vec4& specular );
/** Get the specular value for specified face.*/
const Vec4& getSpecular(const Face face) const;
/** Get the whether specular values are equal for front and back faces.*/
inline const bool getSpecularFrontAndBack() const { return _specularFrontAndBack; }
void setDiffuse( MaterialFace face, const Vec4& diffuse );
const Vec4& getDiffuse(MaterialFace face) const;
bool getDiffuseFrontAndBack() { return _diffuseFrontAndBack; }
/** Set emmision value of specified face(s) of the material,
* valid emmison[0..3] range is 0.0 to 1.0.*/
void setEmission( const Face face, const Vec4& emission );
/** Get the emmsion value for specified face.*/
const Vec4& getEmission(const Face face) const;
/** Get the whether emmision values are equal for front and back faces.*/
inline const bool getEmissionFrontAndBack() const { return _emissionFrontAndBack; }
void setSpecular( MaterialFace face, const Vec4& specular );
const Vec4& getSpecular(MaterialFace face) const;
bool getSpecularFrontAndBack() { return _specularFrontAndBack; }
/** Set shininess of specified face(s) of the material, valid shininess range is 0.0 to 1.0.*/
void setShininess( const Face face, float shininess );
/** Get the shininess value for specified face.*/
const float getShininess(const Face face) const;
/** Get the whether shininess values are equal for front and back faces.*/
inline const bool getShininessFrontAndBack() const { return _shininessFrontAndBack; }
/** Set the alpha value of ambient,diffuse,specular and emmission colors,
* of specified face, to 1-transparancy. Valid transparancy range is 0.0 to 1.0.*/
void setTransparency(const Face face,float trans);
void setEmission( MaterialFace face, const Vec4& emission );
const Vec4& getEmission(MaterialFace face) const;
bool getEmissionFrontAndBack() { return _emissionFrontAndBack; }
void setShininess( MaterialFace face, float shininess );
float getShininess(MaterialFace face) const;
bool getShininessFrontAndBack() { return _shininessFrontAndBack; }
/** Set the alpha value of ambient,diffuse,specular and emmission colors.
* Valid transparancy range is 0.0 to 1.0.*/
void setAlpha(const Face face,float alpha);
protected :
virtual ~Material( void );
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
bool matchFaceAndColor(Input& fr,const char* name,MaterialFace& mf,Vec4& color);
virtual ~Material();
ColorMode _colorMode;

View File

@@ -2,16 +2,28 @@
#define OSG_MATRIX 1
#include <osg/Object>
#include <osg/Types>
#include <osg/Vec3>
#include <osg/Vec4>
#ifdef OSG_USE_IO_DOT_H
#include <iostream.h>
#else
#include <iostream>
using namespace std;
#endif
namespace osg {
class Input;
class Output;
/** 4x4 Matrix for storage & manipulation of transformations in scene graph.
Provides basic maths operations, IO and via osg::Object reference counting.
You can directly load the matrix with OpenGL's LoadMatrixf() function via
the public member _mat as the matrix is stored in the OpenGL format.
Caution: The disadvantage of this feature is, that the matrix access is
'transposed' if you compare it with the standard C/C++ 2d-array-access
convention . I.e. _mat[i][j] accesses the ith column of the jth row in the
4x4 matrix.
*/
class SG_EXPORT Matrix : public Object
{
public:
@@ -26,14 +38,19 @@ class SG_EXPORT Matrix : public Object
virtual ~Matrix();
static Matrix* instance();
virtual Object* clone() const { return new Matrix(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<Matrix*>(obj)!=NULL; }
virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const Matrix*>(obj)!=NULL; }
virtual const char* className() const { return "Matrix"; }
void makeIdent();
void set(const float* m);
void set( float a00, float a01, float a02, float a03,
float a10, float a11, float a12, float a13,
float a20, float a21, float a22, float a23,
float a30, float a31, float a32, float a33);
void copy(const Matrix& matrix);
void makeScale(float sx, float sy, float sz);
@@ -52,6 +69,13 @@ class SG_EXPORT Matrix : public Object
void postTrans( float tx, float ty, float tz );
/**
* Calc the rotation matrix which aligns vector \a old_vec with
* vector \a new_vec. Both \a old_vec and \a new_vec must have
* length 1.0.
*/
void makeRot( const Vec3& old_vec, const Vec3& new_vec );
void makeRot( float deg, float x, float y, float z );
void preRot( float deg, float x, float y, float z, const Matrix& m );
void postRot( const Matrix& m, float deg, float x, float y, float z );
@@ -69,8 +93,24 @@ class SG_EXPORT Matrix : public Object
Matrix operator * (const Matrix& m) const;
/** apply apply an 3x3 transform of v*M[0..2,0..2] */
inline static Vec3 transform3x3(const Vec3& v,const Matrix& m);
/** apply apply an 3x3 transform of M[0..2,0..2]*v */
inline static Vec3 transform3x3(const Matrix& m,const Vec3& v);
/** post multipy v. ie. (m*v) */
inline Vec3 operator * (const Vec3& v) const;
inline friend Vec3 operator * (const Vec3& v,const Matrix& m);
/** pre multipy v. ie. (v*m) */
friend inline Vec3 operator * (const Vec3& v,const Matrix& m);
/** post multipy v. ie. (m*v) */
inline Vec4 operator * (const Vec4& v) const;
/** pre multipy v. ie. (v*m) */
friend inline Vec4 operator * (const Vec4& v,const Matrix& m);
friend inline ostream& operator << (ostream& output, const Matrix& matrix);
bool invert(const Matrix& m);
@@ -78,12 +118,8 @@ class SG_EXPORT Matrix : public Object
float _mat[4][4];
protected:
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
};
// post multiple v. ie. (m*v)
inline Vec3 Matrix::operator * (const Vec3& v) const
{
float d = 1.0f/(_mat[3][0]*v.x()+_mat[3][1]*v.y()+_mat[3][2]*v.z()+_mat[3][3]) ;
@@ -93,7 +129,6 @@ inline Vec3 Matrix::operator * (const Vec3& v) const
}
// pre multiple v. ie. (v*m)
inline Vec3 operator * (const Vec3& v,const Matrix& m)
{
float d = 1.0f/(m._mat[0][3]*v.x()+m._mat[1][3]*v.y()+m._mat[2][3]*v.z()+m._mat[3][3]) ;
@@ -102,6 +137,48 @@ inline Vec3 operator * (const Vec3& v,const Matrix& m)
(m._mat[0][2]*v.x() + m._mat[1][2]*v.y() + m._mat[2][2]*v.z() + m._mat[3][2])*d);
}
inline Vec4 Matrix::operator * (const Vec4& v) const
{
return Vec4( (_mat[0][0]*v.x() + _mat[0][1]*v.y() + _mat[0][2]*v.z() + _mat[0][3]*v.w()),
(_mat[1][0]*v.x() + _mat[1][1]*v.y() + _mat[1][2]*v.z() + _mat[1][3]*v.w()),
(_mat[2][0]*v.x() + _mat[2][1]*v.y() + _mat[2][2]*v.z() + _mat[2][3]*v.w()),
(_mat[3][0]*v.x() + _mat[3][1]*v.y() + _mat[3][2]*v.z() + _mat[3][3]*v.w())) ;
}
inline Vec4 operator * (const Vec4& v,const Matrix& m)
{
return Vec4( (m._mat[0][0]*v.x() + m._mat[1][0]*v.y() + m._mat[2][0]*v.z() + m._mat[3][0]*v.w()),
(m._mat[0][1]*v.x() + m._mat[1][1]*v.y() + m._mat[2][1]*v.z() + m._mat[3][1]*v.w()),
(m._mat[0][2]*v.x() + m._mat[1][2]*v.y() + m._mat[2][2]*v.z() + m._mat[3][2]*v.w()),
(m._mat[0][3]*v.x() + m._mat[1][3]*v.y() + m._mat[2][3]*v.z() + m._mat[3][3]*v.w()));
}
inline Vec3 Matrix::transform3x3(const Vec3& v,const Matrix& m)
{
return Vec3( (m._mat[0][0]*v.x() + m._mat[1][0]*v.y() + m._mat[2][0]*v.z()),
(m._mat[0][1]*v.x() + m._mat[1][1]*v.y() + m._mat[2][1]*v.z()),
(m._mat[0][2]*v.x() + m._mat[1][2]*v.y() + m._mat[2][2]*v.z()));
}
inline Vec3 Matrix::transform3x3(const Matrix& m,const Vec3& v)
{
return Vec3( (m._mat[0][0]*v.x() + m._mat[0][1]*v.y() + m._mat[0][2]*v.z()),
(m._mat[1][0]*v.x() + m._mat[1][1]*v.y() + m._mat[1][2]*v.z()),
(m._mat[2][0]*v.x() + m._mat[2][1]*v.y() + m._mat[2][2]*v.z()) ) ;
}
inline ostream& operator << (ostream& output, const Matrix& matrix)
{
output << "{"<<endl
<< " " << matrix._mat[0][0] << " " << matrix._mat[0][1] << " " << matrix._mat[0][2] << " " << matrix._mat[0][3] << endl
<< " " << matrix._mat[1][0] << " " << matrix._mat[1][1] << " " << matrix._mat[1][2] << " " << matrix._mat[1][3] << endl
<< " " << matrix._mat[2][0] << " " << matrix._mat[2][1] << " " << matrix._mat[2][2] << " " << matrix._mat[2][3] << endl
<< " " << matrix._mat[3][0] << " " << matrix._mat[3][1] << " " << matrix._mat[3][2] << " " << matrix._mat[3][3] << endl
<< "}" << endl;
return output; // to enable cascading
}
};
#endif

View File

@@ -1,9 +1,11 @@
#ifndef OSG_NODE
#define OSG_NODE 1
#include <osg/Types>
#include <osg/Object>
#include <osg/StateSet>
#include <osg/BoundingSphere>
#include <osg/MemoryAdapter>
#include <osg/ref_ptr>
#include <string>
#include <vector>
@@ -13,39 +15,6 @@ namespace osg {
class NodeVisitor;
class Group;
/** Class for adapting the memory management of external data.
* Typically used to specify the memory management of user data
* which can be attached to osg::Node.
*/
class SG_EXPORT MemoryAdapter : public Referenced
{
public:
MemoryAdapter() {}
/** Increment the reference count of the userData.*/
virtual void incrementReference(void* /*userData*/) = 0;
/** Decrement the reference count of the userData.
Is usually implemented such that if reference count
is decremented to zero the userData should be
deleted. However, this is entirely up to the
discression of the user who is extending this base class.*/
virtual void decrementReference(void* /*userData*/) = 0;
/** not current used, but will be used in future.*/
virtual void* clone(void* /*userData*/) { return 0L; }
/** not current used, but will be used in future.*/
virtual bool write(Output& /*fw*/,void* /*userData*/) { return false; }
/** not current used, but will be used in future.*/
virtual bool read(Input& /*fr*/,void* /*userData*/) { return false; }
protected:
virtual ~MemoryAdapter() {}
};
/** Base class for all internal nodes in the scene graph.
Provides interface for most common node operations (Composite Pattern).
*/
@@ -60,11 +29,9 @@ class SG_EXPORT Node : public Object
/** return a shallow copy of a node, with Object* return type.*/
virtual Object* clone() const { return new Node(); }
/** return a shallow copy of a node, with Node* return type.*/
Node* cloneNode() const { return (Node*)clone(); }
/** return true if this and obj are of the same kind of object.*/
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<Node*>(obj)!=NULL; }
virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const Node*>(obj)!=NULL; }
/** return the name of the node's class type.*/
virtual const char* className() const { return "Node"; }
@@ -78,54 +45,66 @@ class SG_EXPORT Node : public Object
/** Set the name of node using C++ style string.*/
void setName( const std::string& name ) { _name = name; }
inline void setName( const std::string& name ) { _name = name; }
/** Set the name of node using a C style string.*/
void setName( const char* name ) { _name = name; }
inline void setName( const char* name ) { _name = name; }
/** Get the name of node.*/
const std::string& getName( void ) { return _name; }
inline const std::string& getName() const { return _name; }
/** 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. */
const ParentList& getParents() const { return _parents; }
inline const ParentList& getParents() const { return _parents; }
/** Get the a copy of parent list of node. A copy is returned to
* prevent modifiaction of the parent list.*/
// inline ParentList getParents() { return _parents; }
inline Group* getParent(const int i) { return _parents[i]; }
/**
* Get a single parent of node.
* Get a single const parent of node.
* @param i index of the parent to get.
* @return the parent i.
*/
Group* getParent(int i) const { return _parents[i]; }
inline const Group* getParent(const int i) const { return _parents[i]; }
/**
* Get the number of parents of node.
* @return the number of parents of this node.
*/
int getNumParents() const { return _parents.size(); }
inline const int getNumParents() const { return _parents.size(); }
/**
* Set user data. See MemoryAdapter documention for details
* of how to specify memory managament of _userData.
*/
void setUserData(void* data,MemoryAdapter* ma=0L)
inline void setUserData(void* data,MemoryAdapter* ma=0L)
{
if (_userData && _memoryAdapter.valid()) _memoryAdapter->decrementReference(_userData);
if (_userData && _memoryAdapter.valid()) _memoryAdapter->unref_data(_userData);
_userData = data;
_memoryAdapter = ma;
if (_userData && _memoryAdapter.valid()) _memoryAdapter->incrementReference(_userData);
if (_userData && _memoryAdapter.valid()) _memoryAdapter->ref_data(_userData);
}
/** Get user data.*/
void* getUserData() const { return _userData; }
inline void* getUserData() { return _userData; }
/** Get const user data.*/
inline const void* getUserData() const { return _userData; }
/** Get the memory adapter associated with _userData.*/
MemoryAdapter* getMemoryAdapter() const { return _memoryAdapter.get(); }
inline MemoryAdapter* getMemoryAdapter() { return _memoryAdapter.get(); }
/** Get the const memory adapter associated with _userData.*/
inline const MemoryAdapter* getMemoryAdapter() const { return _memoryAdapter.get(); }
typedef unsigned int NodeMask;
/** Set the node mask. Note, node mask is will be replaced by TraversalMask.*/
void setNodeMask(NodeMask nm) { _nodeMask = nm; }
inline void setNodeMask(const NodeMask nm) { _nodeMask = nm; }
/** Get the node Mask. Note, node mask is will be replaced by TraversalMask.*/
NodeMask getNodeMask() { return _nodeMask; }
inline const NodeMask getNodeMask() const { return _nodeMask; }
@@ -133,21 +112,36 @@ class SG_EXPORT Node : public Object
typedef std::vector<std::string> DescriptionList;
/** Get the description list of the const node.*/
const DescriptionList& getDescriptions() const { return _descriptions; }
inline const DescriptionList& getDescriptions() const { return _descriptions; }
/** Get the description list of the const node.*/
DescriptionList& getDescriptions() { return _descriptions; }
inline DescriptionList& getDescriptions() { return _descriptions; }
/** Get a single const description of the const node.*/
const std::string& getDescription(int i) const { return _descriptions[i]; }
inline const std::string& getDescription(const int i) const { return _descriptions[i]; }
/** Get a single description of the node.*/
std::string& getDescription(int i) { return _descriptions[i]; }
inline std::string& getDescription(const int i) { return _descriptions[i]; }
/** Get the number of descriptions of the node.*/
int getNumDescriptions() const { return _descriptions.size(); }
inline const int getNumDescriptions() const { return _descriptions.size(); }
/** Add a description string to the node.*/
void addDescription(const std::string& desc) { _descriptions.push_back(desc); }
/** set the node's StateSet.*/
inline void setStateSet(osg::StateSet* dstate) { _dstate = dstate; }
/** return the node's StateSet.*/
inline osg::StateSet* getStateSet() { return _dstate.get(); }
/** return the node's const StateSet.*/
inline const osg::StateSet* getStateSet() const { return _dstate.get(); }
/** get the bounding sphere of node.
Using lazy evaluation computes the bounding sphere if it is 'dirty'.*/
const BoundingSphere& getBound();
inline const BoundingSphere& getBound() const
{
if(!_bsphere_computed) computeBound();
return _bsphere;
}
/** Mark this node's bounding sphere dirty.
Forcing it to be computed on the next call to getBound().*/
@@ -165,29 +159,14 @@ class SG_EXPORT Node : public Object
= new Node().*/
virtual ~Node();
/**
* Template Method Pattern : read local data from .osg file.
* Note should be implemented in derived classes, which
* call their parent class's readLocalData.
* @return true if the input iterator has been advanced, otherwise false.
*/
virtual bool readLocalData(Input& fr);
/**
* Template Method Pattern : read local data from .osg file.
* Note should be implemented in derivied classes, which
* call their parent class's writeLocalData.
* @return true if data has been written out, otherwise false.
*/
virtual bool writeLocalData(Output& fw);
/** 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 bool computeBound( void ) ;
virtual const bool computeBound() const;
BoundingSphere _bsphere;
bool _bsphere_computed;
mutable BoundingSphere _bsphere;
mutable bool _bsphere_computed;
std::string _name;
@@ -201,6 +180,8 @@ class SG_EXPORT Node : public Object
DescriptionList _descriptions;
ref_ptr<StateSet> _dstate;
};
/** A vector of Nodes pointers which is used to describe the path from a root node to a descendant.*/

View File

@@ -9,11 +9,11 @@ class Geode;
class Billboard;
class LightSource;
class Group;
class DCS;
class Transform;
class LOD;
class Sequence;
class Scene;
class Switch;
class Impostor;
/** Visitor for type safe operations on osg::Node's.
Based on GOF's Visitor pattern.*/
@@ -32,21 +32,27 @@ class SG_EXPORT NodeVisitor : public Referenced
NodeVisitor(TraversalMode tm=TRAVERSE_NONE);
virtual ~NodeVisitor();
/** Method to call to reset visitor. Useful for your visitor accumulates
state during a traversal, and you plan to resuse the visitor.
To flush that state for the next traversal than call reset() prior
to each traversal.*/
virtual void reset() {}
/** Set the traversal mode for Node::traverse() to use when
deciding which children of a node to traverse. If a
NodeVisitor has been attached via setTraverseVisitor()
and the new mode is not TRAVERSE_VISITOR then the attached
visitor is detached. Default mode is TRAVERSE_NONE.*/
void setTraverseMode(TraversalMode mode);
void setTraversalMode(const TraversalMode mode);
/** Get the traversal mode.*/
TraversalMode getTraverseMode() { return _traverseMode; }
/** Set a visitor to handle traversal.
Overides the traverse mode setting it to TRAVERSE_VISITOR.*/
inline const TraversalMode getTraversalMode() const { return _traversalMode; }
void setTraverseVisitor(NodeVisitor* nv);
/** Get the traverse visitor, returns NULL if none is attached.*/
NodeVisitor* getTraverseVisitor() { return _traverseVisitor; }
/** Set a visitor to handle traversal.
Overides the traverse mode setting it to TRAVERSAL_VISITOR.*/
void setTraversalVisitor(NodeVisitor* nv);
/** Get the traversal visitor, returns NULL if none is attached.*/
NodeVisitor* getTraversalVisitor() { return _traversalVisitor.get(); }
/** Inline method for passing handling traversal of a nodes.
If you intend to use the visitor for actively traversing
@@ -54,28 +60,28 @@ class SG_EXPORT NodeVisitor : public Referenced
this method unless they handle traversal directly.*/
void traverse(Node& node)
{
if (_traverseVisitor) node.accept(*_traverseVisitor);
else if (_traverseMode==TRAVERSE_PARENTS) node.ascend(*this);
else if (_traverseMode!=TRAVERSE_NONE) node.traverse(*this);
if (_traversalVisitor.valid()) node.accept(*_traversalVisitor);
else if (_traversalMode==TRAVERSE_PARENTS) node.ascend(*this);
else if (_traversalMode!=TRAVERSE_NONE) node.traverse(*this);
}
virtual void apply(Node& node) { traverse(node);}
virtual void apply(Node& node) { traverse(node);}
virtual void apply(Geode& node) { apply((Node&)node); }
virtual void apply(Billboard& node){ apply((Geode&)node); }
virtual void apply(Geode& node) { apply((Node&)node); }
virtual void apply(Billboard& node) { apply((Geode&)node); }
virtual void apply(LightSource& node){ apply((Node&)node); }
virtual void apply(Group& node) { apply((Node&)node); }
virtual void apply(DCS& node) { apply((Group&)node); }
virtual void apply(Switch& node) { apply((Group&)node); }
virtual void apply(Sequence& node) { apply((Group&)node); }
virtual void apply(LOD& node) { apply((Group&)node); }
virtual void apply(Scene& node) { apply((Group&)node); }
virtual void apply(Group& node) { apply((Node&)node); }
virtual void apply(Transform& node) { apply((Group&)node); }
virtual void apply(Switch& node) { apply((Group&)node); }
virtual void apply(Sequence& node) { apply((Group&)node); }
virtual void apply(LOD& node) { apply((Group&)node); }
virtual void apply(Impostor& node) { apply((LOD&)node); }
protected:
NodeVisitor* _traverseVisitor;
TraversalMode _traverseMode;
ref_ptr<NodeVisitor> _traversalVisitor;
TraversalMode _traversalMode;
};

View File

@@ -6,59 +6,84 @@
#ifdef OSG_USE_IO_DOT_H
#include <iostream.h>
#include <fstream.h>
//#include <stdlib.h>
#else
#include <iostream>
#include <fstream>
//#include <stdlib.h>
using namespace std;
#endif
namespace osg {
/** Range of notify levels from DEBUG_FP through to FATAL, ALWAYS
* is reserved for forcing the absorption of all messages. The
* keywords are also used verbatim when specified by the environmental
* variable OSGNOTIFYLEVEL. See documentation on osg::notify() for
* further details.
*/
enum NotifySeverity {
ALWAYS=0,
FATAL=1,
WARN=2,
NOTICE=3,
INFO=4,
DEBUG=5,
FP_DEBUG=6
DEBUG_INFO=5,
DEBUG_FP=6
};
extern NotifySeverity g_NotifyLevel;
extern ofstream *g_absorbStreamPtr;
/** global notify level. */
SG_EXPORT extern NotifySeverity g_NotifyLevel;
/** set the notify level, overriding the default or value set by
* the environmental variable OSGNOTIFYLEVEL.
*/
SG_EXPORT extern void setNotifyLevel(NotifySeverity severity);
SG_EXPORT extern int getNotifyLevel();
/** get the notify level. */
SG_EXPORT extern NotifySeverity getNotifyLevel();
/** initialize notify level. */
SG_EXPORT extern bool initNotifyLevel();
/** notify messaging function for providing fatal through to verbose
* debugging messages. Level of messages sent to the console can
* be controlled by setting the NotifyLevel either within your
* application or via the an environmental variable. For instance
* setenv OSGNOTIFYLEVEL DEBUG (for tsh), export OSGNOTIFYLEVEL=DEBUG
* (for bourne shell) or set OSGNOTIFYLEVEL=DEBUG (for Windows) all
* set tell the osg to redirect all debugging and more important messages
* to the console (useful for debugging :-) setting ALWAYS will force
* all messages to be absorbed, which might be appropriate for final
* applications. Default NotifyLevel is NOTICE. Check the enum
* NotifySeverity for full range of possibilities. To use the notify
* with your code simply use the notify function as a normal file
* stream (like cout) i.e osg::notify(osg::DEBUG) << "Hello Bugs!"<<endl;
*/
inline ostream& notify(const NotifySeverity severity=INFO)
{
static bool s_initialized = initNotifyLevel();
#ifdef __GNUC__
/* a little hack to prevent gcc's warning message (will be optimized away) */
if ( 0 && s_initialized )
;
#endif
#ifdef WIN32
inline ostream& notify(NotifySeverity severity=INFO)
{
if (severity<=osg::WARN) return cerr;
else return cout;
static ofstream s_abosorbStr("nul");
#else
static ofstream s_abosorbStr("/dev/null");
#endif
if (severity<=g_NotifyLevel)
{
if (severity<=osg::WARN) return cerr;
else return cout;
}
return s_abosorbStr;
}
#else
SG_EXPORT extern ostream& notify(NotifySeverity severity=INFO);
#endif
// A nifty_counter to ensure that the notify things are initialised before
// they're used. Initialises g_NotifyLevel and g_absorbStreamPointer
class SG_EXPORT NotifyInit
{
public:
NotifyInit();
~NotifyInit();
private:
static int count_;
};
static NotifyInit niftyNotifyInit;
};
#endif

View File

@@ -5,9 +5,6 @@
namespace osg {
class Input;
class Output;
/** Base class/standard interface for objects which require IO support,
cloning and reference counting.
Based on GOF Composite, Prototype and Template Method patterns.
@@ -25,23 +22,12 @@ class SG_EXPORT Object : public Referenced
Must be defined by derived classes.*/
virtual Object* clone() const = 0;
virtual bool isSameKindAs(Object*) { return true; }
virtual bool isSameKindAs(const Object*) const { return true; }
/** return the name of the object's class type. Must be defined
by derived classes.*/
virtual const char* className() const = 0;
/** Template Method/Prototype Pattern : create a clone and read
Object data from Input. Reads Input and if it matches this
objects className() then create a clone and match '{' brackets
and repeating calling Object::readLocalData() until the
matching ']' is read.*/
virtual Object* readClone(Input& fr);
/** Template Method Pattern : write out Object data to Output.
Sequence of output is className() followed by Open '{'
and then call Object::writeLocalData() and complete with '}'.*/
virtual bool write(Output& fw);
protected:
/** Object destructor. Note, is protected so that Objects cannot
@@ -53,17 +39,6 @@ class SG_EXPORT Object : public Referenced
= new Node().*/
virtual ~Object() {}
/** Template Method Pattern : read local data from .osg file.
Note should be implemented in derivied classes, which
call their parent class's readLocalData. Returns
true if the input iterator has been advanced, otherwise false.*/
virtual bool readLocalData(Input&) { return false; }
/** Template Method Pattern : write local data to .osg file.
Note should be implemented in derivied classes, which
call their parent class's writeLocalData. Returns
true if data has been written out, otherwise false.*/
virtual bool writeLocalData(Output&) { return false; }
private:
/** disallow any form of deep copy.*/

View File

@@ -1,33 +1,39 @@
#ifndef OSG_POINT
#define OSG_POINT 1
#include <osg/Export>
#include <osg/Object>
#include <osg/Vec3>
#include <osg/StateAttribute>
#include <osg/StateSet>
namespace osg {
class Input;
class Output;
class SG_EXPORT Point : public Object
/** Point - encapsulates the OpenGL point smmothing and size state.*/
class SG_EXPORT Point : public StateAttribute
{
public :
Point();
static Point* instance();
virtual Object* clone() const { return new Point(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<Point*>(obj)!=NULL; }
virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const Point*>(obj)!=NULL; }
virtual const char* className() const { return "Point"; }
void setSize(float size);
void setFadeThresholdSize(float fadeThresholdSize);
virtual const Type getType() const { return POINT; }
virtual void setStateSetModes(StateSet& ds,const GLModeValue value) const
{
ds.setMode(GL_POINT_SMOOTH,value);
}
void setSize(const float size);
inline const float getSize() const { return _size; }
void setFadeThresholdSize(const float fadeThresholdSize);
inline const float getFadeThresholdSize() const { return _fadeThresholdSize; }
void setDistanceAttenuation(const Vec3& distanceAttenuation);
inline const Vec3& getDistanceAttenuation() const { return _distanceAttenuation; }
static void enableSmooth( void );
static void disableSmooth( void );
void apply( void );
virtual void apply(State& state) const;
static void init_GL_EXT();
@@ -35,9 +41,6 @@ class SG_EXPORT Point : public Object
virtual ~Point();
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
float _size;
float _fadeThresholdSize;
Vec3 _distanceAttenuation;

View File

@@ -1,39 +1,42 @@
#ifndef OSG_POLYGONOFFSET
#define OSG_POLYGONOFFSET 1
#include <osg/Export>
#include <osg/Object>
#include <osg/Vec3>
#include <osg/StateAttribute>
#include <osg/StateSet>
namespace osg {
class Input;
class Output;
class SG_EXPORT PolygonOffset : public Object
/** PolygonOffset - encapsulates the OpenGL glPolygonOffset state.*/
class SG_EXPORT PolygonOffset : public StateAttribute
{
public :
PolygonOffset();
static PolygonOffset* instance();
virtual Object* clone() const { return new PolygonOffset(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<PolygonOffset*>(obj)!=NULL; }
virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const PolygonOffset*>(obj)!=NULL; }
virtual const char* className() const { return "PolygonOffset"; }
void setOffset(float factor,float units);
virtual const Type getType() const { return POLYGONOFFSET; }
static void enable( void );
static void disable( void );
virtual void setStateSetModes(StateSet& ds,const GLModeValue value) const
{
ds.setMode(GL_POLYGON_OFFSET_FILL,value);
ds.setMode(GL_POLYGON_OFFSET_LINE,value);
ds.setMode(GL_POLYGON_OFFSET_POINT,value);
}
void apply( void );
inline void setFactor(const float factor) { _factor = factor; }
inline const float getFactor() const { return _factor; }
inline void setUnits(const float units) { _units = units; }
inline const float getUnits() const { return _units; }
virtual void apply(State& state) const;
protected :
virtual ~PolygonOffset();
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
float _factor;
float _units;

View File

@@ -1,11 +1,8 @@
#ifndef OSG_QUAT
#define OSG_QUAT 1
#include <osg/Export>
#include <math.h>
#include <osg/Vec4>
#include <osg/Vec3>
#include <osg/Vec4>
#include <osg/Matrix>
namespace osg {
@@ -28,30 +25,39 @@ class SG_EXPORT Quat
---------------------------------------------------------- */
Vec4 _fv; // a four-vector
/* ----------------------------------
CONSTRUCTORS
Default constructor
One to accept four floats
One to accept a Vec4
These are implemented in Quat.cpp
---------------------------------- */
Quat( void );
Quat( float x, float y, float z, float w );
Quat( const Vec4& vec );
Quat() {}
Quat( float x, float y, float z, float w ): _fv(x,y,z,w) {}
Quat( const Vec4& v ): _fv(v) {}
/* ----------------------------------
Methods to access data members
---------------------------------- */
inline Vec4 asVec4( void ) const
inline Vec4& asVec4()
{
return _fv;
}
inline Vec3 asVec3( void ) const
inline const Vec4& asVec4() const
{
return _fv;
}
inline const Vec3 asVec3() const
{
return Vec3(_fv[0], _fv[1], _fv[2]);
}
inline void set(const float x, const float y, const float z, const float w)
{
_fv.set(x,y,z,w);
}
inline void set(const osg::Vec4& v)
{
_fv = v;
}
/* -------------------------------------------------------------
BASIC ARITHMETIC METHODS
Implemented in terms of Vec4s. Some Vec4 operators, e.g.
@@ -60,7 +66,7 @@ class SG_EXPORT Quat
Also define methods for conjugate and the multiplicative inverse.
------------------------------------------------------------- */
/// Multiply by scalar
inline Quat operator * (const float& rhs) const
inline const Quat operator * (const float& rhs) const
{
return Quat(_fv*rhs);
}
@@ -73,7 +79,7 @@ class SG_EXPORT Quat
}
/// Binary multiply
inline Quat operator*(const Quat& rhs) const
inline const Quat operator*(const Quat& rhs) const
{
return Quat( _fv[3]*rhs._fv[0] + _fv[0]*rhs._fv[3] + _fv[1]*rhs._fv[2] - _fv[2]*rhs._fv[1],
_fv[3]*rhs._fv[1] - _fv[0]*rhs._fv[2] + _fv[1]*rhs._fv[3] + _fv[2]*rhs._fv[0],
@@ -97,7 +103,7 @@ class SG_EXPORT Quat
}
/// Divide by scalar
inline Quat operator / (const float& rhs) const
inline const Quat operator / (const float& rhs) const
{
return Quat(_fv/rhs);
}
@@ -110,7 +116,7 @@ class SG_EXPORT Quat
}
/// Binary divide
inline Quat operator/(const Quat& denom) const
inline const Quat operator/(const Quat& denom) const
{
return ( (*this) * denom.inverse() );
}
@@ -123,7 +129,7 @@ class SG_EXPORT Quat
}
/// Binary addition
inline Quat operator + (const Quat& rhs) const
inline const Quat operator + (const Quat& rhs) const
{
return Quat( _fv + rhs._fv );
}
@@ -136,7 +142,7 @@ class SG_EXPORT Quat
}
/// Binary subtraction
inline Quat operator - (const Quat& rhs) const
inline const Quat operator - (const Quat& rhs) const
{
return Quat( _fv - rhs._fv );
}
@@ -150,31 +156,31 @@ class SG_EXPORT Quat
/** Negation operator - returns the negative of the quaternion.
Basically just calls operator - () on the Vec4 */
inline Quat operator - () const
inline const Quat operator - () const
{
return Quat ( -_fv );
}
/// Length of the quaternion = sqrt( vec . vec )
float length( void ) const
const float length() const
{
return _fv.length();
}
/// Length of the quaternion = vec . vec
float length2( void ) const
const float length2() const
{
return _fv.length2();
}
/// Conjugate
inline Quat conj ( void ) const
inline const Quat conj () const
{
return Quat( -_fv[0], -_fv[1], -_fv[2], _fv[3] );
}
/// Multiplicative inverse method: q^(-1) = q^*/(q.q^*)
inline Quat inverse ( void ) const
inline const Quat inverse () const
{
return conj() / length2();
}
@@ -215,17 +221,18 @@ class SG_EXPORT Quat
/** Get the equivalent matrix for this quaternion.*/
void get( osg::Matrix& m ) const;
friend inline ostream& operator << (ostream& output, const Quat& vec)
{
output << vec._fv[0] << " "
<< vec._fv[1] << " "
<< vec._fv[2] << " "
<< vec._fv[3];
return output; // to enable cascading
}
friend inline ostream& operator << (ostream& output, const Quat& vec);
}; // end of class prototype
inline ostream& operator << (ostream& output, const Quat& vec)
{
output << vec._fv[0] << " "
<< vec._fv[1] << " "
<< vec._fv[2] << " "
<< vec._fv[3];
return output; // to enable cascading
}
}; // end of namespace
#endif

View File

@@ -2,100 +2,35 @@
#define OSG_REFERENCED 1
#include <osg/Export>
#include <set>
namespace osg {
/** Convience functor for unreferencing objects.*/
template<class T>
struct UnrefOp
{
void operator () (T* node) { node->unref(); }
};
/** Smart pointer for handling referenced counted objects.*/
template<class T>
class ref_ptr
{
public:
ref_ptr() :_ptr(0L) {}
ref_ptr(T* t):_ptr(t) { if (_ptr) _ptr->ref(); }
ref_ptr(const ref_ptr& rp):_ptr(rp._ptr) { if (_ptr) _ptr->ref(); }
~ref_ptr() { if (_ptr) _ptr->unref(); }
ref_ptr& operator = (const ref_ptr& rp)
{
if (_ptr==rp._ptr) return *this;
if (_ptr) _ptr->unref();
_ptr = rp._ptr;
if (_ptr) _ptr->ref();
return *this;
}
ref_ptr& operator = (T* ptr)
{
if (_ptr==ptr) return *this;
if (_ptr) _ptr->unref();
_ptr = ptr;
if (_ptr) _ptr->ref();
return *this;
}
bool operator == (const ref_ptr& rp) const
{
return (_ptr==rp._ptr);
}
bool operator == (const T* ptr) const
{
return (_ptr==ptr);
}
bool operator != (const ref_ptr& rp) const
{
return (_ptr!=rp._ptr);
}
bool operator != (const T* ptr) const
{
return (_ptr!=ptr);
}
T& operator*() const { return *_ptr; }
T* operator->() const { return _ptr; }
bool operator!() const { return _ptr==0L; }
bool valid() const { return _ptr!=0L; }
T* get() const { return _ptr; }
private:
T* _ptr;
};
/** Base class from providing referencing counted objects.*/
class Referenced
class SG_EXPORT Referenced
{
public:
Referenced() { _refCount=0; }
Referenced(Referenced&) { _refCount=0; }
Referenced(const Referenced&) { _refCount=0; }
Referenced& operator = (Referenced&) { return *this; }
inline Referenced& operator = (Referenced&) { return *this; }
/** increment the reference count by one, indicating that
this object has another pointer which is referencing it.*/
void ref() { ++_refCount; }
inline void ref() const { ++_refCount; }
/** decrement the reference count by one, indicating that
a pointer to this object is referencing it. If the
refence count goes to zero, it is assumed that this object
is nolonger referenced and is automatically deleted.*/
void unref() { --_refCount; if (_refCount<=0) delete this; }
inline void unref() const { --_refCount; if (_refCount<=0) delete this; }
/** return the number pointers currently referencing this object. */
int referenceCount() { return _refCount; }
inline const int referenceCount() const { return _refCount; }
protected:
virtual ~Referenced() {};
int _refCount;
virtual ~Referenced() {}
mutable int _refCount;
};
};

View File

@@ -2,19 +2,181 @@
#define OSG_STATE 1
#include <osg/Export>
#include <osg/StateSet>
#include <osg/Matrix>
#include <vector>
#include <map>
namespace osg {
class SG_EXPORT State
/** macro for use with osg::StateAttrbiute::apply methods for detected and
* reporting OpenGL error messages.*/
#define OSG_GL_DEBUG(message) \
if (state.getFineGrainedErrorDetection()) \
{ \
GLenum errorNo = glGetError(); \
if (errorNo!=GL_NO_ERROR) \
{ \
osg::notify(WARN)<<"Warning: detected OpenGL error '"<<gluErrorString(errorNo)<<" "<<message<<endl; \
}\
}
/** State class for managing a state stack.
* Lazy state updating is used to minize state changes.
*/
class SG_EXPORT State : public Referenced
{
public :
State( void );
~State( void );
State();
virtual ~State();
/** push stateset onto state stack.*/
void pushStateSet(const StateSet* dstate);
/** pop drawstate off state stack.*/
void popStateSet();
/** reset the state object to an empty stack.*/
void reset();
/** apply an OpenGL mode if required. */
inline const bool apply_mode(const StateAttribute::GLMode mode,const bool enabled)
{
return apply_mode(mode,enabled,_modeMap[mode]);
}
/** apply an attribute if required. */
inline const bool apply_attribute(const StateAttribute* attribute)
{
return apply_attribute(attribute,_attributeMap[attribute->getType()]);
}
/** apply stateset.*/
void apply(const StateSet* dstate);
/** apply the state.*/
void apply();
/** mode has been set externally, update state to reflect this setting.*/
void have_applied(const StateAttribute::GLMode mode,const StateAttribute::GLModeValue value);
/** attribute has been applied externally, update state to reflect this setting.*/
void have_applied(const StateAttribute* attribute);
/** Set the current OpenGL context uniqueID.
Note, it is the application developers responsiblity to
set up unique ID for each OpenGL context. This value is
then used by osg::StateAttribure's and osg::Drawable's to
help manage OpenGL display list and texture binds appropriate
for each context.*/
inline void setContextID(unsigned int contextID) { _contextID=contextID; }
/** Get the current OpenGL context unique ID.*/
inline const unsigned int getContextID() const { return _contextID; }
/** Set the frame number.*/
inline void setFrameNumber(unsigned int fn) { _frameNumber = fn; }
/** Get the frame number.*/
inline unsigned int getFrameNumber() const { return _frameNumber; }
/** Increment the frame number. Done once per frame.*/
inline void incrementFrameNumber() { ++_frameNumber; }
/** Set the hint to OpenGL routines to do fine grained OpenGL error checking.*/
void setFineGrainedErrorDetection(const bool flag) { _fineGrainedErrorDetection = flag; }
/** Get the hint to OpenGL routines to do fine grained OpenGL error checking.*/
const bool getFineGrainedErrorDetection() const { return _fineGrainedErrorDetection; }
private:
unsigned int _contextID;
unsigned int _frameNumber;
typedef std::vector<StateAttribute::GLModeValue> ValueVec;
struct ModeStack
{
ModeStack()
{
changed = false;
last_applied_value = false;
}
bool changed;
bool last_applied_value;
ValueVec valueVec;
};
typedef std::pair<const StateAttribute*,StateAttribute::OverrideValue> AttributePair;
typedef std::vector<AttributePair> AttributeVec;
struct AttributeStack
{
AttributeStack()
{
changed = false;
last_applied_attribute = 0L;
}
bool changed;
const StateAttribute* last_applied_attribute;
AttributeVec attributeVec;
};
/** apply an OpenGL mode if required, passing in mode, enable flag and appropriate mode stack */
inline const bool apply_mode(const StateAttribute::GLMode mode,const bool enabled,ModeStack& ms)
{
if (ms.last_applied_value != enabled)
{
ms.last_applied_value = enabled;
if (enabled) glEnable(mode);
else glDisable(mode);
return true;
}
else
return false;
}
/** apply an attribute if required, passing in attribute and appropriate attribute stack */
inline const bool apply_attribute(const StateAttribute* attribute,AttributeStack& as)
{
if (as.last_applied_attribute != attribute)
{
as.last_applied_attribute = attribute;
attribute->apply(*this);
return true;
}
else
return false;
}
typedef std::map<StateAttribute::GLMode,ModeStack> ModeMap;
typedef std::map<StateAttribute::Type,AttributeStack> AttributeMap;
typedef std::vector<ref_ptr<const StateSet> > StateSetStack;
typedef std::vector<ref_ptr<const Matrix> > MatrixStack;
ModeMap _modeMap;
AttributeMap _attributeMap;
StateSetStack _drawStateStack;
bool _fineGrainedErrorDetection;
private :
GeoState *initial;
GeoState *req;
GeoState *current;
};
};

View File

@@ -5,7 +5,7 @@
namespace osg {
/** Switch - Group node which allows switching between children.
/** Switch is a Group node which allows switching between children.
Typical uses would be for objects which might need to be rendered
differently at different times, for instance a switch could be used
to represent the different states of a traffic light.
@@ -14,30 +14,44 @@ class SG_EXPORT Switch : public Group
{
public :
/**
* Special mode values for the Switch. Use these if you want to
* turn on/off all child nodes.
*/
enum SwitchType {
ALL_CHILDREN_ON=-1,
ALL_CHILDREN_OFF=-2
/** Turn on all children. */
ALL_CHILDREN_ON=-1,
/** Turn off all children. */
ALL_CHILDREN_OFF=-2
};
Switch();
virtual Object* clone() const { return new Switch(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<Switch*>(obj)!=NULL; }
virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const Switch*>(obj)!=NULL; }
virtual const char* className() const { return "Switch"; }
virtual void accept(NodeVisitor& nv) { nv.apply(*this); }
virtual void traverse(NodeVisitor& nv);
void setVal(int val) { _value = val; }
int getVal() const { return _value; }
/**
* Selects the active child Node or enables a special
* SwitchType mode.
* @param value the number of the active child
* (first child == number 0) or SwitchType. Invalid values
* will be ignored.
*/
inline void setValue(const int value) { _value = value; }
/**
* Returns the number of the active child Node or the SwitchType.
*/
inline const int getValue() const { return _value; }
protected :
virtual ~Switch() {}
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
int _value;
/** The current Switch value. */
int _value;
};
};

View File

@@ -1,43 +1,41 @@
#ifndef OSG_TEXENV
#define OSG_TEXENV 1
#include <osg/Export>
#include <osg/GL>
#include <osg/Object>
#include <osg/StateAttribute>
namespace osg {
class SG_EXPORT TexEnv : public Object
/** TexEnv - encapsulates the OpenGL glTexEnv (texture environment) state.*/
class SG_EXPORT TexEnv : public StateAttribute
{
public :
enum TexEnvMode {
DECAL = GL_DECAL,
MODULATE = GL_MODULATE,
BLEND = GL_BLEND
};
TexEnv( void );
static TexEnv* instance();
virtual Object* clone() const { return new TexEnv(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<TexEnv*>(obj)!=NULL; }
virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const TexEnv*>(obj)!=0L; }
virtual const char* className() const { return "TexEnv"; }
virtual const Type getType() const { return TEXENV; }
void setMode( TexEnvMode mode );
void apply( void );
enum Mode {
DECAL = GL_DECAL,
MODULATE = GL_MODULATE,
BLEND = GL_BLEND,
REPLACE = GL_REPLACE
};
void setMode( const Mode mode );
const Mode getMode() const { return _mode; }
virtual void apply(State& state) const;
protected :
virtual ~TexEnv( void );
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
bool matchModeStr(const char* str,TexEnvMode& mode);
const char* getModeStr(TexEnvMode mode);
TexEnvMode _mode;
Mode _mode;
};
};

View File

@@ -1,51 +1,72 @@
#ifndef OSG_TEXGEN
#define OSG_TEXGEN 1
#include <osg/Export>
#include <osg/GL>
#include <osg/OSG>
#include <osg/Object>
#include <osg/Vec4>
#include <osg/StateAttribute>
#include <osg/StateSet>
namespace osg {
class Input;
class Output;
class SG_EXPORT TexGen : public Object
/** TexGen - encapsulates the OpenGL glTexGen (texture coordinate generation) state.*/
class SG_EXPORT TexGen : public StateAttribute
{
public :
enum TexGenMode {
TexGen( void );
virtual Object* clone() const { return new TexGen(); }
virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const TexGen*>(obj)!=NULL; }
virtual const char* className() const { return "TexGen"; }
virtual const Type getType() const { return TEXGEN; }
virtual void setStateSetModes(StateSet& ds,const GLModeValue value) const
{
ds.setMode(GL_TEXTURE_GEN_S,value);
ds.setMode(GL_TEXTURE_GEN_T,value);
// Not happy with turning all tex gen paramters on
// as the OSG currently only supports 2D textures and therefore
// only S and T will only be required, R&Q would be redundent...
// So commenting out the following until OSG supports 3D texures.
// I plan to revamp the OpenGL state management later so will
// tidy up then. Robert Osfield. Jan 2001.
// The tidy up is now happening, but wiil have a think before
// resolving the below parameters.
// ds.setMode(GL_TEXTURE_GEN_R,value);
// ds.setMode(GL_TEXTURE_GEN_Q,value);
}
virtual void apply(State& state) const;
enum Mode {
OBJECT_LINEAR = GL_OBJECT_LINEAR,
EYE_LINEAR = GL_EYE_LINEAR,
SPHERE_MAP = GL_SPHERE_MAP
};
TexGen( void );
static TexGen* instance();
virtual Object* clone() const { return new TexGen(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<TexGen*>(obj)!=NULL; }
virtual const char* className() const { return "TexGen"; }
inline void setMode( const Mode mode ) { _mode = mode; }
static void enable( void );
static void disable( void );
void apply( void );
const Mode getMode() const { return _mode; }
void setMode( TexGenMode mode ) { _mode = mode; }
enum Coord {
S, T, R, Q
};
void setPlane(const Coord which, const Vec4& plane);
const Vec4& getPlane(const Coord which) const;
protected :
virtual ~TexGen( void );
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
Mode _mode;
bool matchModeStr(const char* str,TexGenMode& mode);
const char* getModeStr(TexGenMode mode);
TexGenMode _mode;
/// additional texgen coefficents for GL_OBJECT_PLANE or GL_EYE_PLANE,
Vec4 _plane_s, _plane_t, _plane_r, _plane_q;
};

View File

@@ -1,26 +1,40 @@
#ifndef OSG_TEXMAT
#define OSG_TEXMAT 1
#include <osg/Export>
#include <osg/StateAttribute>
#include <osg/Matrix>
namespace osg {
class SG_EXPORT TexMat : public Matrix
/** Texture Matrix state class for encapsulating OpenGL texture matrix functionality.*/
class SG_EXPORT TexMat : public StateAttribute
{
public :
TexMat( void );
static TexMat* instance();
virtual Object* clone() const { return new TexMat(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<TexMat*>(obj)!=NULL; }
virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const TexMat*>(obj)!=NULL; }
virtual const char* className() const { return "TexMat"; }
void apply( void );
virtual const Type getType() const { return TEXMAT; }
/** Set the texture matrix */
inline void setMatrix(const Matrix& matrix) { _matrix = matrix; }
/** Get the texture matrix */
inline Matrix& getMatrix() { return _matrix; }
/** Get the const texture matrix */
inline const Matrix& getMatrix() const { return _matrix; }
/** apply as OpenGL texture matrix.*/
virtual void apply(State& state) const;
protected:
virtual ~TexMat( void );
Matrix _matrix;
};
};

View File

@@ -1,33 +1,110 @@
// -*-c++-*-
#ifndef OSG_TEXTURE
#define OSG_TEXTURE 1
#include <osg/Export>
#include <osg/GL>
#include <osg/OSG>
#include <osg/Types>
#include <osg/Image>
#include <osg/StateAttribute>
#include <osg/StateSet>
#include <osg/ref_ptr>
#include <vector>
#include <map>
#include <set>
// if not defined by gl.h use the definition found in:
// http://oss.sgi.com/projects/ogl-sample/registry/EXT/texture_filter_anisotropic.txt
#ifndef GL_TEXTURE_MAX_ANISOTROPY_EXT
#define GL_TEXTURE_MAX_ANISOTROPY_EXT (GLenum)0x84fe
#endif
#ifndef GL_ARB_texture_compression
#define GL_COMPRESSED_ALPHA_ARB 0x84E9
#define GL_COMPRESSED_LUMINANCE_ARB 0x84EA
#define GL_COMPRESSED_LUMINANCE_ALPHA_ARB 0x84EB
#define GL_COMPRESSED_INTENSITY_ARB 0x84EC
#define GL_COMPRESSED_RGB_ARB 0x84ED
#define GL_COMPRESSED_RGBA_ARB 0x84EE
#define GL_TEXTURE_COMPRESSION_HINT_ARB 0x84EF
#define GL_TEXTURE_IMAGE_SIZE_ARB 0x86A0
#define GL_TEXTURE_COMPRESSED_ARB 0x86A1
#define GL_NUM_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A2
#define GL_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A3
#endif
#ifndef GL_EXT_texture_compression_s3tc
#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0
#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1
#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2
#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3
#endif
#ifndef GL_MIRRORED_REPEAT_IBM
#define GL_MIRRORED_REPEAT_IBM 0x8370
#endif
#ifndef GL_GENERATE_MIPMAP_SGIS
#define GL_GENERATE_MIPMAP_SGIS (GLenum)0x8191
#define GL_GENERATE_MIPMAP_HINT_SGIS 0x8192
#endif
namespace osg {
class Input;
class Output;
/** Texture state class which encapsulates OpenGl texture functionality.*/
class SG_EXPORT Texture : public Object
class SG_EXPORT Texture : public StateAttribute
{
public :
Texture();
static Texture* instance();
virtual Object* clone() const { return new Texture(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<Texture*>(obj)!=NULL; }
virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const Texture*>(obj)!=0L; }
virtual const char* className() const { return "Texture"; }
virtual const Type getType() const { return (Type)(TEXTURE_0+_textureUnit); }
virtual void setStateSetModes(StateSet& ds,const GLModeValue value) const
{
ds.setMode(GL_TEXTURE_2D,value);
}
/** Set the texture image. */
void setImage(Image* image);
/** Get the texture image. */
Image* getImage() const { return _image.get(); }
Image* getImage() { return _image.get(); }
/** Get the const texture image. */
inline const Image* getImage() const { return _image.get(); }
/** Copy pixels into a 2D texture image.As per glCopyTexImage2D.
* Creates an OpenGL texture object from the current OpenGL background
* framebuffer contents at pos \a x, \a y with width \a width and
* height \a height. \a width and \a height must be a power of two.
*/
void copyTexImage2D(State& state, int x, int y, int width, int height );
/** Copy a two-dimensional texture subimage. As per glCopyTexSubImage2D.
* Updates portion of an exisiting OpenGL texture object from the current OpenGL background
* framebuffer contents at pos \a x, \a y with width \a width and
* height \a height. \a width and \a height must be a power of two,
* and writing into the texture with offset \a xoffset and \a yoffset.
*/
void copyTexSubImage2D(State& state, int xoffset, int yoffset, int x, int y, int width, int height );
/** Set the texture unit.
* Valid values are 0,1,2,3.
* Default value of texture unit is 0.
* note, multi-texturing not fully implemented yet... April 2001.
*/
inline void setTextureUnit(const unsigned int textureUnit) { _textureUnit = textureUnit; }
/** get the texture unit.*/
inline const unsigned int getTextureUnit() const { return _textureUnit; }
enum WrapParameter {
WRAP_S,
@@ -36,14 +113,15 @@ class SG_EXPORT Texture : public Object
};
enum WrapMode {
CLAMP = GL_CLAMP,
REPEAT = GL_REPEAT
CLAMP = GL_CLAMP,
REPEAT = GL_REPEAT,
MIRROR = GL_MIRRORED_REPEAT_IBM
};
/** Set the texture wrap mode.*/
void setWrap(WrapParameter which, WrapMode wrap);
void setWrap(const WrapParameter which, const WrapMode wrap);
/** Get the texture wrap mode.*/
WrapMode getWrap(WrapParameter which) const;
const WrapMode getWrap(const WrapParameter which) const;
enum FilterParameter {
@@ -57,46 +135,161 @@ class SG_EXPORT Texture : public Object
LINEAR_MIPMAP_NEAREST = GL_LINEAR_MIPMAP_NEAREST,
NEAREST = GL_NEAREST,
NEAREST_MIPMAP_LINEAR = GL_NEAREST_MIPMAP_LINEAR,
NEAREST_MIPMAP_NEAREST = GL_NEAREST_MIPMAP_NEAREST
NEAREST_MIPMAP_NEAREST = GL_NEAREST_MIPMAP_NEAREST,
ANISOTROPIC = GL_TEXTURE_MAX_ANISOTROPY_EXT
};
/** Set the texture filter mode.*/
void setFilter(FilterParameter which, FilterMode filter);
void setFilter(const FilterParameter which, const FilterMode filter);
/** Get the texture filter mode.*/
FilterMode getFilter(FilterParameter which) const;
const FilterMode getFilter(const FilterParameter which) const;
/** Enable OpenGL texturing.*/
static void enable( void );
/** Disable OpenGL texturing.*/
static void disable( void );
enum InternalFormatMode {
USE_IMAGE_DATA_FORMAT,
USE_USER_DEFINED_FORMAT,
USE_ARB_COMPRESSION,
USE_S3TC_DXT1_COMPRESSION,
USE_S3TC_DXT3_COMPRESSION,
USE_S3TC_DXT5_COMPRESSION
};
/** On first apply, create the minmapped texture and bind it,
subsequent apply will simple bind to texture.*/
void apply( void );
/** Set the internal format mode.
* Note, If the mode is set USE_IMAGE_DATA_FORMAT, USE_ARB_COMPRESSION,
* USE_S3TC_COMPRESSION the internalFormat is automatically selected,
* and will overwrite the previous _internalFormatValue.
*/
inline void setInternalFormatMode(const InternalFormatMode mode) { _internalFormatMode = mode; }
/** Get the internal format mode.*/
inline const InternalFormatMode getInternalFormatMode() const { return _internalFormatMode; }
/** Set the internal format to use when creating OpenGL textures.
* Also sets the internalFormatMode to USE_USER_DEFINED_FORMAT.
*/
inline void setInternalFormatValue(const int internalFormat)
{
_internalFormatMode = USE_USER_DEFINED_FORMAT;
_internalFormatValue = internalFormat;
}
/** Get the internal format to use when creating OpenGL textures.*/
inline const int getInternalFormatValue() const { return _internalFormatValue; }
/** return the OpenGL texture object for specified context.*/
inline const uint getTextureObject(const uint contextID) const { if (contextID<_handleList.size()) return _handleList[contextID]; else return 0;}
/** return the memory size of texture object.
* Texture object size can be used for estimating the cost of
* uploading the texture to graphics hardware, which inturn can
* be used for setting texture residence priorities. */
inline const uint getTextureObjectSize() const { return _textureObjectSize; }
enum SubloadMode {
OFF,
AUTO,
IF_DIRTY
};
/** Set the texture subload mode. */
inline void setSubloadMode(const SubloadMode mode) { _subloadMode = mode; }
/** Get the texture subload mode. */
inline const SubloadMode getSubloadMode() const { return _subloadMode; }
/** Set the texture subload offsets. */
inline void setSubloadOffset(const int x, const int y) {
_subloadOffsX = x;
_subloadOffsY = y;
}
/** Get the texture subload offsets. */
inline void getSubloadOffset(int& x, int& y) const {
x = _subloadOffsX;
y = _subloadOffsY;
}
/** Get the handle to the texture object for the current context.*/
inline uint& getHandle(const uint contextID) const
{
// pad out handle list if required.
while (_handleList.size()<=contextID)
_handleList.push_back(0);
// get the globj for the current contextID.
return _handleList[contextID];
}
/** Force a recompile on next apply() of associated OpenGL texture objects.*/
void dirtyTextureObject();
/** On first apply (unless already compiled), create the minmapped
* texture and bind it, subsequent apply will simple bind to texture.*/
virtual void apply(State& state) const;
/** Compile the texture mip maps. Implemented by simply calling apply().*/
virtual void compile(State& state) const;
/** Method which does the creation of the texture itself, and
* does not set or use texture binding. */
virtual void applyImmediateMode(State& state) const;
/** use deleteTextureObject instead of glDeleteTextures to allow
* OpenGL texture objects to cached until they can be deleted
* by the OpenGL context in which they were created, specified
* by contextID.*/
static void deleteTextureObject(uint contextID,uint handle);
/** flush all the cached display list which need to be deleted
* in the OpenGL context related to contextID.*/
static void flushDeletedTextureObjects(uint contextID);
protected :
virtual ~Texture();
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
typedef std::vector<uint> TextureNameList;
mutable TextureNameList _handleList;
uint _handle;
typedef std::vector<uint> ImageModifiedTag;
mutable ImageModifiedTag _modifiedTag;
ref_ptr<Image> _image;
// size of the created OpenGL texture object, may be estimated.
mutable uint _textureObjectSize;
bool matchWrapStr(const char* str,WrapMode& wrap);
const char* getWrapStr(WrapMode wrap);
// not ideal that _image is mutable, but its required since
// Image::ensureDimensionsArePowerOfTwo() can only be called
// in a valid OpenGL context, a therefore within an Texture::apply
// which is const...
mutable ref_ptr<Image> _image;
bool matchFilterStr(const char* str,FilterMode& filter);
const char* getFilterStr(FilterMode filter);
unsigned int _textureUnit;
WrapMode _wrap_s;
WrapMode _wrap_t;
WrapMode _wrap_r;
FilterMode _min_filter;
FilterMode _mag_filter;
InternalFormatMode _internalFormatMode;
int _internalFormatValue;
// subloaded images can have different texture and image sizes.
mutable unsigned int _textureWidth, _textureHeight;
SubloadMode _subloadMode;
unsigned int _subloadOffsX, _subloadOffsY;
// static cache of deleted display lists which can only
// by completely deleted once the appropriate OpenGL context
// is set.
typedef std::map<uint,std::set<uint> > DeletedTextureObjectCache;
static DeletedTextureObjectCache s_deletedTextureObjectCache;
};
};

View File

@@ -3,14 +3,22 @@
#include <osg/Export>
#ifdef macintosh
//#define __TIMESIZE_DOUBLE__
#include <ctime>
#endif
namespace osg {
#ifdef WIN32
typedef __int64 Timer_t;
#elif defined macintosh
typedef double Timer_t;
#else
typedef unsigned long long Timer_t;
#endif
/** A high resolution, low latency time stamper.*/
class SG_EXPORT Timer {
public:
@@ -23,8 +31,8 @@ class SG_EXPORT Timer {
#pragma optimize("",off)
inline Timer_t tick( void )
{
volatile Timer_t ts;
volatile unsigned int HighPart;
volatile Timer_t ts;
volatile unsigned int HighPart;
volatile unsigned int LowPart;
_asm
{
@@ -32,23 +40,29 @@ class SG_EXPORT Timer {
xor edx, edx // not supported or minimal overhead
_emit 0x0f // desired
_emit 0x31 //
mov HighPart,edx
mov LowPart,eax
mov HighPart,edx
mov LowPart,eax
}
//ts = LowPart | HighPart >> 32;
*((unsigned int*)&ts) = LowPart;
//ts = LowPart | HighPart >> 32;
*((unsigned int*)&ts) = LowPart;
*((unsigned int*)&ts+1) = HighPart;
return ts;
}
#pragma optimize("",on)
#endif
#ifdef __linux
#if defined(__linux) || defined(__FreeBSD__)
#define CLK(x) __asm__ volatile (".byte 0x0f, 0x31" : "=A" (x))
inline Timer_t tick( void ) {Timer_t x;CLK(x);return x;}
#endif
#ifdef __sgi
inline Timer_t tick( void ) { return *clk; }
#endif
#ifdef macintosh
// because __TIMESIZE_DOUBLE__ is defined
// clock resolution is now: 100000 CLOCKS_PER_SEC instead of 60
inline Timer_t tick( void ) { return std::clock(); }
#endif
double delta_s( Timer_t t1, Timer_t t2 );
double delta_m( Timer_t t1, Timer_t t2 );

View File

@@ -1,17 +1,28 @@
#ifndef OSG_TRANSPARENCY
#define OSG_TRANSPARENCY 1
#include <osg/Export>
#include <osg/Object>
#include <osg/GL>
#include <osg/StateAttribute>
#include <osg/StateSet>
namespace osg {
class SG_EXPORT Transparency : public Object
/** Transparancy - encapsulates the OpenGL transparancy state.*/
class SG_EXPORT Transparency : public StateAttribute
{
public :
Transparency();
virtual Object* clone() const { return new Transparency(); }
virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const Transparency*>(obj)!=0L; }
virtual const char* className() const { return "Transparency"; }
virtual const Type getType() const { return TRANSPARENCY; }
virtual void setStateSetModes(StateSet& ds,const GLModeValue value) const
{
ds.setMode(GL_BLEND,value);
}
enum TransparencyMode {
DST_ALPHA = GL_DST_ALPHA,
DST_COLOR = GL_DST_COLOR,
@@ -26,16 +37,19 @@ class SG_EXPORT Transparency : public Object
ZERO = GL_ZERO
};
Transparency();
static Transparency * instance();
virtual Object* clone() const { return new Transparency(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<Transparency*>(obj)!=NULL; }
virtual const char* className() const { return "Transparency"; }
inline void setFunction( const int source, const int destination )
{
_source_factor = source;
_destination_factor = destination;
}
void setFunction( int source, int destination );
static void enable( void );
static void disable( void );
void apply( void );
void setSource(const int source) { _source_factor = source; }
inline const int getSource() const { return _source_factor; }
void setDestination(const int destination) { _destination_factor = destination; }
inline const int getDestination() const { return _destination_factor; }
virtual void apply(State& state) const;
protected :

View File

@@ -1,9 +1,6 @@
#ifndef OSG_TYPES
#define OSG_TYPES 1
#include <osg/Export>
#include <osg/Vec3>
namespace osg {
typedef unsigned int uint;
@@ -11,7 +8,7 @@ typedef unsigned short ushort;
typedef unsigned char uchar;
typedef uchar ubyte;
#ifdef WIN32
#if defined(WIN32) || defined (macintosh)
#define M_E 2.7182818284590452354
#define M_LOG2E 1.4426950408889634074
#define M_LOG10E 0.43429448190325182765

View File

@@ -1,7 +1,6 @@
#ifndef OSG_VEC2
#define OSG_VEC2 1
#include <osg/Export>
#include <math.h>
#ifdef OSG_USE_IO_DOT_H
@@ -29,7 +28,14 @@ class Vec2
float _v[2];
bool operator == (const Vec2& v) const { return _v[0]==v._v[0] && _v[1]==v._v[1]; }
const bool operator == (const Vec2& v) const { return _v[0]==v._v[0] && _v[1]==v._v[1]; }
const bool operator < (const Vec2& v) const
{
if (_v[0]<v._v[0]) return true;
else if (_v[0]>v._v[0]) return false;
else return (_v[1]<v._v[1]);
}
inline float* ptr() { return _v; }
inline const float* ptr() const { return _v; }
@@ -37,22 +43,22 @@ class Vec2
inline void set( float x, float y ) { _v[0]=x; _v[1]=y; }
inline float& operator [] (int i) { return _v[i]; }
inline float operator [] (int i) const { return _v[i]; }
inline const float operator [] (int i) const { return _v[i]; }
inline float& x() { return _v[0]; }
inline float& y() { return _v[1]; }
inline float x() const { return _v[0]; }
inline float y() const { return _v[1]; }
inline const float x() const { return _v[0]; }
inline const float y() const { return _v[1]; }
/// dot product
inline float operator * (const Vec2& rhs) const
inline const float operator * (const Vec2& rhs) const
{
return _v[0]*rhs._v[0]+_v[1]*rhs._v[1];
}
/// multiply by scalar
inline Vec2 operator * (const float& rhs) const
inline const Vec2 operator * (const float& rhs) const
{
return Vec2(_v[0]*rhs, _v[1]*rhs);
}
@@ -66,7 +72,7 @@ class Vec2
}
/// divide by scalar
inline Vec2 operator / (const float& rhs) const
inline const Vec2 operator / (const float& rhs) const
{
return Vec2(_v[0]/rhs, _v[1]/rhs);
}
@@ -80,7 +86,7 @@ class Vec2
}
/// binary vector add
inline Vec2 operator + (const Vec2& rhs) const
inline const Vec2 operator + (const Vec2& rhs) const
{
return Vec2(_v[0]+rhs._v[0], _v[1]+rhs._v[1]);
}
@@ -95,7 +101,7 @@ class Vec2
}
/// binary vector subract
inline Vec2 operator - (const Vec2& rhs) const
inline const Vec2 operator - (const Vec2& rhs) const
{
return Vec2(_v[0]-rhs._v[0], _v[1]-rhs._v[1]);
}
@@ -109,26 +115,26 @@ class Vec2
}
/// negation operator. Returns the negative of the Vec2
inline Vec2 operator - () const
inline const Vec2 operator - () const
{
return Vec2 (-_v[0], -_v[1]);
}
/// Length of the vector = sqrt( vec . vec )
inline float length() const
inline const float length() const
{
return sqrtf( _v[0]*_v[0] + _v[1]*_v[1] );
}
/// Length squared of the vector = vec . vec
inline float length2( void ) const
inline const float length2( void ) const
{
return _v[0]*_v[0] + _v[1]*_v[1];
}
/** normalize the vector so that it has length unity
returns the previous length of the vector*/
inline float normalize()
inline const float normalize()
{
float norm = Vec2::length();
_v[0] /= norm;

View File

@@ -1,7 +1,6 @@
#ifndef OSG_VEC3
#define OSG_VEC3 1
#include <osg/Export>
#include <math.h>
#ifdef OSG_USE_IO_DOT_H
@@ -28,7 +27,16 @@ class Vec3
float _v[3];
bool operator == (const Vec3& v) const { return _v[0]==v._v[0] && _v[1]==v._v[1] && _v[2]==v._v[2]; }
inline const bool operator == (const Vec3& v) const { return _v[0]==v._v[0] && _v[1]==v._v[1] && _v[2]==v._v[2]; }
inline const bool operator < (const Vec3& v) const
{
if (_v[0]<v._v[0]) return true;
else if (_v[0]>v._v[0]) return false;
else if (_v[1]<v._v[1]) return true;
else if (_v[1]>v._v[1]) return false;
else return (_v[2]<v._v[2]);
}
inline float* ptr() { return _v; }
inline const float* ptr() const { return _v; }
@@ -39,15 +47,15 @@ class Vec3
}
inline float& operator [] (int i) { return _v[i]; }
inline float operator [] (int i) const { return _v[i]; }
inline const float operator [] (int i) const { return _v[i]; }
inline float& x() { return _v[0]; }
inline float& y() { return _v[1]; }
inline float& z() { return _v[2]; }
inline float x() const { return _v[0]; }
inline float y() const { return _v[1]; }
inline float z() const { return _v[2]; }
inline const float x() const { return _v[0]; }
inline const float y() const { return _v[1]; }
inline const float z() const { return _v[2]; }
/// dot product
inline float operator * (const Vec3& rhs) const
@@ -56,7 +64,7 @@ class Vec3
}
/// cross product
inline Vec3 operator ^ (const Vec3& rhs) const
inline const Vec3 operator ^ (const Vec3& rhs) const
{
return Vec3(_v[1]*rhs._v[2]-_v[2]*rhs._v[1],
_v[2]*rhs._v[0]-_v[0]*rhs._v[2] ,
@@ -64,7 +72,7 @@ class Vec3
}
/// multiply by scalar
inline Vec3 operator * (const float& rhs) const
inline const Vec3 operator * (const float& rhs) const
{
return Vec3(_v[0]*rhs, _v[1]*rhs, _v[2]*rhs);
}
@@ -79,7 +87,7 @@ class Vec3
}
/// divide by scalar
inline Vec3 operator / (const float& rhs) const
inline const Vec3 operator / (const float& rhs) const
{
return Vec3(_v[0]/rhs, _v[1]/rhs, _v[2]/rhs);
}
@@ -94,7 +102,7 @@ class Vec3
}
/// binary vector add
inline Vec3 operator + (const Vec3& rhs) const
inline const Vec3 operator + (const Vec3& rhs) const
{
return Vec3(_v[0]+rhs._v[0], _v[1]+rhs._v[1], _v[2]+rhs._v[2]);
}
@@ -110,7 +118,7 @@ class Vec3
}
/// binary vector subract
inline Vec3 operator - (const Vec3& rhs) const
inline const Vec3 operator - (const Vec3& rhs) const
{
return Vec3(_v[0]-rhs._v[0], _v[1]-rhs._v[1], _v[2]-rhs._v[2]);
}
@@ -125,26 +133,26 @@ class Vec3
}
/// negation operator. Returns the negative of the Vec3
inline Vec3 operator - () const
inline const Vec3 operator - () const
{
return Vec3 (-_v[0], -_v[1], -_v[2]);
}
/// Length of the vector = sqrt( vec . vec )
inline float length( void ) const
inline const float length() const
{
return sqrtf( _v[0]*_v[0] + _v[1]*_v[1] + _v[2]*_v[2] );
}
/// Length squared of the vector = vec . vec
inline float length2( void ) const
inline const float length2() const
{
return _v[0]*_v[0] + _v[1]*_v[1] + _v[2]*_v[2];
}
/** normalize the vector so that it has length unity
returns the previous length of the vector*/
inline float normalize()
inline const float normalize()
{
float norm = Vec3::length();
_v[0] /= norm;
@@ -153,16 +161,18 @@ class Vec3
return( norm );
}
friend inline ostream& operator << (ostream& output, const Vec3& vec)
{
output << vec._v[0] << " "
<< vec._v[1] << " "
<< vec._v[2];
return output; // to enable cascading
}
friend inline ostream& operator << (ostream& output, const Vec3& vec);
}; // end of class Vec3
inline ostream& operator << (ostream& output, const Vec3& vec)
{
output << vec._v[0] << " "
<< vec._v[1] << " "
<< vec._v[2];
return output; // to enable cascading
}
} // end of namespace osg
#endif

View File

@@ -1,7 +1,6 @@
#ifndef OSG_VEC4
#define OSG_VEC4 1
#include <osg/Export>
#include <math.h>
#ifdef OSG_USE_IO_DOT_H
@@ -33,7 +32,18 @@ class Vec4
float _v[4];
bool operator == (const Vec4& v) const { return _v[0]==v._v[0] && _v[1]==v._v[1] && _v[2]==v._v[2] && _v[3]==v._v[3]; }
inline const bool operator == (const Vec4& v) const { return _v[0]==v._v[0] && _v[1]==v._v[1] && _v[2]==v._v[2] && _v[3]==v._v[3]; }
inline const bool operator < (const Vec4& v) const
{
if (_v[0]<v._v[0]) return true;
else if (_v[0]>v._v[0]) return false;
else if (_v[1]<v._v[1]) return true;
else if (_v[1]>v._v[1]) return false;
else if (_v[2]<v._v[2]) return true;
else if (_v[2]>v._v[2]) return false;
else return (_v[3]<v._v[3]);
}
inline float* ptr() { return _v; }
inline const float* ptr() const { return _v; }
@@ -43,8 +53,8 @@ class Vec4
_v[0]=x; _v[1]=y; _v[2]=z; _v[3]=w;
}
inline float& operator [] (int i) { return _v[i]; }
inline float operator [] (int i) const { return _v[i]; }
inline float& operator [] (const int i) { return _v[i]; }
inline float operator [] (const int i) const { return _v[i]; }
inline float& x() { return _v[0]; }
inline float& y() { return _v[1]; }
@@ -133,26 +143,26 @@ class Vec4
}
/// negation operator. Returns the negative of the Vec4
inline Vec4 operator - () const
inline const Vec4 operator - () const
{
return Vec4 (-_v[0], -_v[1], -_v[2], -_v[3]);
}
/// Length of the vector = sqrt( vec . vec )
inline float length( void ) const
inline const float length() const
{
return sqrtf( _v[0]*_v[0] + _v[1]*_v[1] + _v[2]*_v[2] + _v[3]*_v[3]);
}
/// Length squared of the vector = vec . vec
inline float length2( void ) const
inline const float length2() const
{
return _v[0]*_v[0] + _v[1]*_v[1] + _v[2]*_v[2] + _v[3]*_v[3];
}
/** normalize the vector so that it has length unity
returns the previous length of the vector*/
inline float normalize()
inline const float normalize()
{
float norm = Vec4::length();
_v[0] /= norm;

View File

@@ -0,0 +1,72 @@
#ifndef OSGDB_DOTOSGWRAPPER
#define OSGDB_DOTOSGWRAPPER 1
#include <osg/ref_ptr>
#include <osg/Object>
#include <osgDB/Input>
#include <osgDB/Output>
#include <string>
#include <vector>
//#include <stdlib.h>
namespace osgDB {
/** Wrapper class for specifing read and write functions for extending
* the .osg file format. */
class OSGDB_EXPORT DotOsgWrapper : public osg::Referenced
{
public:
typedef std::vector<std::string> Associates;
typedef bool (*ReadFunc)(osg::Object&,osgDB::Input&);
typedef bool (*WriteFunc)(const osg::Object&,osgDB::Output&);
enum ReadWriteMode
{
READ_AND_WRITE,
READ_ONLY
};
DotOsgWrapper(osg::Object* proto,
const std::string& name,
const std::string& associates,
ReadFunc readFunc,
WriteFunc writeFunc,
ReadWriteMode readWriteMode=READ_AND_WRITE);
inline const osg::Object* getPrototype() const { return _prototype.get(); }
inline const std::string& getName() const { return _name; }
inline const Associates& getAssociates() const { return _associates; }
inline ReadFunc getReadFunc() const { return _readFunc; }
inline WriteFunc getWriteFunc() const { return _writeFunc; }
inline ReadWriteMode getReadWriteMode() const { return _readWriteMode; }
protected:
/// protected to prevent inappropriate creation of wrappers.
DotOsgWrapper() {}
/// protected to prevent inappropriate creation of wrappers.
DotOsgWrapper(DotOsgWrapper&):osg::Referenced() {}
/// protected to prevent wrapper being created on stack.
virtual ~DotOsgWrapper() {}
osg::ref_ptr<osg::Object> _prototype;
std::string _name;
Associates _associates;
ReadFunc _readFunc;
WriteFunc _writeFunc;
ReadWriteMode _readWriteMode;
};
};
#endif

View File

@@ -0,0 +1,63 @@
#ifndef OSG_DYNAMICLIBRARY
#define OSG_DYNAMICLIBRARY 1
#include <osg/Referenced>
#include <osgDB/Export>
#include <string>
namespace osgDB {
/** DynamicLibrary - encapsulates the loading and unloading of dynamic libraries,
typically used for loading ReaderWriter plug-ins.
*/
class OSGDB_EXPORT DynamicLibrary : public osg::Referenced
{
public:
typedef void* HANDLE;
typedef void* PROC_ADDRESS;
/** returns a pointer to a DynamicLibrary object on successfully
* opening of library returns NULL on failure.
*/
static DynamicLibrary* loadLibrary(const std::string& libraryName);
/** return name of library stripped of path.*/
const std::string& getName() const { return _name; }
/** return name of library including full path to it.*/
const std::string& getFullName() const { return _fullName; }
/** return handle to .dso/.dll dynamic library itself.*/
HANDLE getHandle() const { return _handle; }
/** return address of function located in library.*/
PROC_ADDRESS getProcAddress(const std::string& procName);
protected:
/** disallow default constructor.*/
DynamicLibrary():osg::Referenced() {}
/** disallow copy constructor.*/
DynamicLibrary(const DynamicLibrary&):osg::Referenced() {}
/** disallow copy operator.*/
DynamicLibrary& operator == (const DynamicLibrary&) { return *this; }
/** Disallow public construction so that users have to go
* through loadLibrary() above which returns NULL on
* failure, a valid DynamicLibrary object on success.
*/
DynamicLibrary(const std::string& name,HANDLE handle);
~DynamicLibrary();
HANDLE _handle;
std::string _name;
std::string _fullName;
};
};
#endif // __DYNAMIC_LIBRARY_H

21
include/osgDB/Export Normal file
View File

@@ -0,0 +1,21 @@
#ifndef OSGDB_EXPORT_
#define OSGDB_EXPORT_ 1
#ifdef WIN32
#pragma warning( disable : 4251 )
#pragma warning( disable : 4275 )
#pragma warning( disable : 4786 )
#endif
#if defined(_MSC_VER)
# ifdef OSGDB_LIBRARY
# define OSGDB_EXPORT __declspec(dllexport)
# else
# define OSGDB_EXPORT __declspec(dllimport)
# endif /* OSGDBSG_LIBRARY */
#else
# define OSGDB_EXPORT
#endif
#endif

106
include/osgDB/Field Normal file
View File

@@ -0,0 +1,106 @@
#ifndef OSGDB_FIELD
#define OSGDB_FIELD 1
#include <osg/Types>
#include <osgDB/Export>
#include <string>
#include <stdlib.h>
namespace osgDB {
class OSGDB_EXPORT Field
{
public:
enum {
MIN_CACHE_SIZE = 256
};
Field();
Field(const Field& field);
virtual ~Field();
virtual Field& operator = (const Field& ic);
void reset();
void addChar(char c);
int getNoCharacters() const { return _fieldCacheSize; }
void setWithinQuotes(bool withinQuotes=true);
bool getWithinQuotes();
void setNoNestedBrackets(int no);
int getNoNestedBrackets();
enum FieldType
{
OPEN_BRACKET,
CLOSE_BRACKET,
STRING,
WORD,
REAL,
INTEGER,
BLANK,
UNINTIALISED
};
FieldType getFieldType() const;
bool isValid() const;
bool isOpenBracket() const;
bool isCloseBracket() const;
bool isWord() const;
bool matchWord(const char* str) const;
bool matchWord(const char* str,int noCharacters) const;
bool isString() const;
bool matchString(const char* str) const;
bool matchString(const char* str,int noCharacters) const;
bool isQuotedString() const;
const char* getStr() const;
char* takeStr();
bool isInt() const;
bool matchInt(int i) const;
bool getInt(int& i) const;
bool isUInt() const;
bool matchUInt(osg::uint i) const;
bool getUInt(osg::uint& i) const;
bool isFloat() const;
bool matchFloat(float f) const;
bool getFloat(float& f) const;
bool isDouble() const;
bool matchDouble(double f) const;
bool getDouble(double& d) const;
static FieldType calculateFieldType(const char* str,bool withinQuotes=false);
protected:
void _init();
void _free();
void _copy(const Field& ic);
int _fieldCacheCapacity;
int _fieldCacheSize;
char* _fieldCache;
mutable FieldType _fieldType;
bool _withinQuotes;
int _noNestedBrackets;
};
};
#endif // __SG_FIELD_H

63
include/osgDB/FieldReader Normal file
View File

@@ -0,0 +1,63 @@
#ifndef OSGDB_FIELDREADER
#define OSGDB_FIELDREADER 1
#include <osgDB/Export>
#include <string.h>
#include <stdlib.h>
#ifdef OSG_USE_IO_DOT_H
#include <iostream.h>
#else
#include <iostream>
using namespace std;
#endif
namespace osgDB {
class Field;
class OSGDB_EXPORT FieldReader
{
public:
FieldReader();
FieldReader(const FieldReader& ic);
virtual ~FieldReader();
virtual FieldReader& operator = (const FieldReader& ic);
void attach(istream* input);
void detach();
virtual bool eof() const;
bool readField(Field& fieldPtr);
void ignoreField();
/** no of unmatched `{' encounterd so far in file*/
int getNoNestedBrackets() const;
private:
bool _readField(Field* fieldPtr);
void _init();
void _free();
void _copy(const FieldReader& ic);
istream* _fin;
bool _eof;
bool findStartOfNextField();
int _noNestedBrackets;
bool _delimiterEatLookUp[256];
bool _delimiterKeepLookUp[256];
};
};
#endif // __SG_FIELD_READER_H

View File

@@ -0,0 +1,68 @@
#ifndef OSGDB_FIELDREADERITERATOR
#define OSGDB_FIELDREADERITERATOR 1
#include <osgDB/Field>
#include <osgDB/FieldReader>
namespace osgDB {
class OSGDB_EXPORT FieldReaderIterator
{
public:
enum {
MINIMUM_FIELD_READER_QUEUE_SIZE = 10
};
FieldReaderIterator();
FieldReaderIterator(const FieldReaderIterator& ic);
virtual ~FieldReaderIterator();
virtual FieldReaderIterator& operator = (const FieldReaderIterator& ic);
void attach(istream* input);
void detach();
virtual bool eof() const;
FieldReader& getFieldReader() { return _reader; }
void insert(int pos,Field* field);
void insert(int pos,const char* str);
Field& operator [] (int pos);
Field& field (int pos);
FieldReaderIterator& operator ++ ();
FieldReaderIterator& operator += (int no);
/** increments the itetor of the next simple field or
whole block if the current field[0] is an open bracket */
void advanceOverCurrentFieldOrBlock();
void advanceToEndOfCurrentBlock();
void advanceToEndOfBlock(int noNestBrackets);
bool matchSequence(const char* str);
private:
void _init();
void _free();
void _copy(const FieldReaderIterator& ic);
FieldReader _reader;
Field _blank;
Field* _previousField;
Field** _fieldQueue;
int _fieldQueueSize;
int _fieldQueueCapacity;
};
};
#endif // __OSGDB_FIELD_READER_QUEUE_H

View File

@@ -0,0 +1,21 @@
#ifndef OSGDB_FILENAMEUTILS
#define OSGDB_FILENAMEUTILS 1
#include <osgDB/Export>
#include <string>
namespace osgDB {
OSGDB_EXPORT extern std::string getFilePath(const std::string& filename);
OSGDB_EXPORT extern std::string getFileExtension(const std::string& filename);
OSGDB_EXPORT extern std::string getLowerCaseFileExtension(const std::string& filename);
OSGDB_EXPORT extern std::string getSimpleFileName(const std::string& fileName);
OSGDB_EXPORT extern std::string getStrippedName(const std::string& fileName);
OSGDB_EXPORT extern bool equalCaseInsensitive(const std::string& lhs,const std::string& rhs);
OSGDB_EXPORT extern bool equalCaseInsensitive(const std::string& lhs,const char* rhs);
};
#endif

46
include/osgDB/FileUtils Normal file
View File

@@ -0,0 +1,46 @@
#ifndef OSGDB_FILEUTILS
#define OSGDB_FILEUTILS 1
#include <osgDB/Export>
#include <vector>
#include <string>
namespace osgDB {
/** initialize the data file path,
* uses OSGFILEPATH environmental
* variable to defined.*/
OSGDB_EXPORT extern void initFilePath( void );
/** set the data file path.*/
OSGDB_EXPORT extern void setFilePath( const char *_path );
/** set the data file path.*/
OSGDB_EXPORT extern const char* getFilePath();
/** find specified file on the set data file path.*/
OSGDB_EXPORT extern char *findFile( const char *file );
/** find specified dso/dll.*/
OSGDB_EXPORT extern char *findDSO( const char *name );
/** simple list of names to represent a directory's contents. */
typedef std::vector<std::string> DirectoryContents;
/** return the directory/filename of a file if its is contained within specified directory.
* return "" if directory does not contain file. If caseInsensitive is set to true then
* a case insenstive comparision is used to compare fileName to directory contents.
* This is useful when unix programs attempt read case insentive windows filenames.
*/
OSGDB_EXPORT extern std::string findFileInDirectory(const std::string& fileName,const std::string& dirName,bool caseInsensitive=false);
/** return the contents of a directory.
* returns an empty array on any error.*/
OSGDB_EXPORT extern DirectoryContents getDirectoryContents(const std::string& dirName);
};
#endif

48
include/osgDB/Input Normal file
View File

@@ -0,0 +1,48 @@
#ifndef OSGDB_INPUT
#define OSGDB_INPUT 1
#include <osg/Image>
#include <osg/Node>
#include <osg/Drawable>
#include <osg/StateAttribute>
#include <osgDB/FieldReaderIterator>
#include <map>
#include <string>
namespace osgDB {
/** Class for managing the reading of ASCII .osg files.*/
class OSGDB_EXPORT Input : public FieldReaderIterator
{
public:
Input();
virtual ~Input();
virtual osg::Object* readObjectOfType(const osg::Object& compObj);
virtual osg::Object* readObject();
virtual osg::Image* readImage();
virtual osg::Drawable* readDrawable();
virtual osg::StateAttribute* readStateAttribute();
virtual osg::Node* readNode();
virtual osg::Object* readObject(const std::string& fileName);
virtual osg::Image* readImage(const std::string& fileName);
virtual osg::Node* readNode(const std::string& fileName);
virtual osg::Object* getObjectForUniqueID(const std::string& uniqueID);
virtual void regisiterUniqueIDForObject(const std::string& uniqueID,osg::Object* obj);
private:
typedef std::map<std::string,osg::Object*> UniqueIDToObjectMapping;
UniqueIDToObjectMapping _uniqueIDToObjectMap;
};
};
#endif // __SG_INPUT_H

120
include/osgDB/Output Normal file
View File

@@ -0,0 +1,120 @@
#ifndef OSGDB_OUTPUT
#define OSGDB_OUTPUT 1
#include <osg/Object>
#include <osgDB/Export>
#include <string>
#include <map>
#ifdef OSG_USE_IO_DOT_H
#include <fstream.h>
#else
#include <fstream>
using namespace std;
#endif
namespace osgDB {
/** ofstream wrapper class for adding support for indenting.
Used in output of .osg ASCII files to improve their readability.*/
class OSGDB_EXPORT Output : public ofstream
{
public:
Output();
Output(const char* name);
virtual ~Output();
void open(const char *name);
void open(const char *name,int mode);
Output& indent();
inline const int getIndentStep() const { return _indentStep; }
inline void setIndentStep(int step) { _indentStep = step; }
inline const int getIndent() const { return _indent; }
inline void setIndent(int indent) { _indent = indent; }
inline const int getNumIndicesPerLine() const { return _numIndicesPerLine; }
inline void setNumIndicesPerLine(int num) { _numIndicesPerLine = num; }
void moveIn();
void moveOut();
virtual bool writeObject(const osg::Object& obj);
bool getUniqueIDForObject(const osg::Object* obj,std::string& uniqueID);
bool createUniqueIDForObject(const osg::Object* obj,std::string& uniqueID);
bool registerUniqueIDForObject(const osg::Object* obj,std::string& uniqueID);
enum PathNameHint
{
AS_IS,
FULL_PATH,
RELATIVE_PATH,
FILENAME_ONLY
};
inline void setPathNameHint(const PathNameHint pnh) { _pathNameHint = pnh; }
inline const PathNameHint getPathNameHint() const { return _pathNameHint; }
virtual const std::string getFileNameForOutput(const std::string& filename) const;
protected:
// prevent copy construction and assignment.
Output(const Output&) : ofstream() {}
Output& operator = (const Output&) { return *this; }
virtual void init();
int _indent;
int _indentStep;
int _numIndicesPerLine;
typedef std::map<const osg::Object*,std::string> UniqueIDToLabelMapping;
UniqueIDToLabelMapping _objectToUniqueIDMap;
std::string _filename;
PathNameHint _pathNameHint;
};
template<class T>
bool writeArrayBlock(Output& fw,T* start,T* finish)
{
fw.indent() << "{" << endl;
fw.moveIn();
int numIndicesThisLine = 0;
for(T* itr=start;itr!=finish;++itr)
{
if (numIndicesThisLine>=fw.getNumIndicesPerLine())
{
fw << endl;
numIndicesThisLine = 0;
}
if (numIndicesThisLine==0) fw.indent();
else fw << " ";
fw << *itr;
++numIndicesThisLine;
}
fw << endl;
fw.moveOut();
fw.indent() << "}" << endl;
return true;
}
};
#endif // __SG_OUTPUT_H

39
include/osgDB/ReadFile Normal file
View File

@@ -0,0 +1,39 @@
#ifndef OSGDB_READFILE
#define OSGDB_READFILE 1
#include <osg/Node>
#include <osg/Image>
#include <osgDB/Export>
#include <string>
namespace osgDB {
/** Read an osg::Object from file.
* Return valid osg::Object on sucess,
* return NULL on failure.
* The osgDB::Registry is used to load the appropriate ReaderWriter plugin
* for the filename extension, and this plugin then handles the request
* to read the specified file.*/
OSGDB_EXPORT extern osg::Object* readObjectFile(const std::string& filename);
/** Read an osg::Image from file.
* Return valid osg::Image on sucess,
* return NULL on failure.
* The osgDB::Registry is used to load the appropriate ReaderWriter plugin
* for the filename extension, and this plugin then handles the request
* to read the specified file.*/
OSGDB_EXPORT extern osg::Image* readImageFile(const std::string& filename);
/** Read an osg::Node from file.
* Return valid osg::Node on sucess,
* return NULL on failure.
* The osgDB::Registry is used to load the appropriate ReaderWriter plugin
* for the filename extension, and this plugin then handles the request
* to read the specified file.*/
OSGDB_EXPORT extern osg::Node* readNodeFile(const std::string& filename);
};
#endif

View File

@@ -0,0 +1,33 @@
#ifndef OSGDB_READERWRITER
#define OSGDB_READERWRITER 1
#include <osg/Referenced>
#include <osg/Image>
#include <osg/Node>
#include <string>
namespace osgDB {
/** pure virtual base class for reading and writing of non native formats. */
class OSGDB_EXPORT ReaderWriter : public osg::Referenced
{
public:
virtual ~ReaderWriter() {}
virtual const char* className() = 0;
virtual bool acceptsExtension(const std::string& /*extension*/) { return false; }
virtual osg::Object* readObject(const std::string& /*fileName*/) { return NULL; }
virtual osg::Image* readImage(const std::string& /*fileName*/) { return NULL; }
virtual osg::Node* readNode(const std::string& /*fileName*/) { return NULL; }
virtual bool writeObject(const osg::Object& /*obj*/,const std::string& /*fileName*/) {return false; }
virtual bool writeImage(const osg::Image& /*image*/,const std::string& /*fileName*/) {return false; }
virtual bool writeNode(const osg::Node& /*node*/,const std::string& /*fileName*/) { return false; }
};
};
#endif // OSG_READERWRITER

181
include/osgDB/Registry Normal file
View File

@@ -0,0 +1,181 @@
#ifndef OSGDB_REGISTRY
#define OSGDB_REGISTRY 1
#include <vector>
#include <map>
#include <string>
#include <osg/ref_ptr>
#include <osgDB/DynamicLibrary>
#include <osgDB/ReaderWriter>
#include <osgDB/DotOsgWrapper>
namespace osgDB {
/**
Registry is a singleton factory which stores
the Objects types available at runtime for loading,
and any Object reader or writers which are linked in
at runtime for reading non-native file formats.
The RegisterObjectProxy can be used to automatically register
at runtime a Object with the Registry.
The RegisterReaderWriterProxy can be used to automatically
register at runtime a reader/writer with the Registry.
*/
class OSGDB_EXPORT Registry
{
public:
~Registry();
static Registry* instance();
/** register an .fileextension alias to mapExt toExt, the later
* should the the extension name of the readerwriter plugin library.
* For example to map .tif files to the tiff loader, use
* addExtAlias("tif","tiff") which will enable .tif to be read
* by the libdb_tiff readerwriter plugin.*/
void addFileExtensionAlias(const std::string mapExt, const std::string toExt);
void addDotOsgWrapper(DotOsgWrapper* wrapper);
void removeDotOsgWrapper(DotOsgWrapper* wrapper);
void addReaderWriter(ReaderWriter* rw);
void removeReaderWriter(ReaderWriter* rw);
/** create the platform specific library name associated with file.*/
std::string createLibraryNameForFile(const std::string& fileName);
/** create the platform specific library name associated with file extension.*/
std::string createLibraryNameForExt(const std::string& ext);
/** find the library in the SG_LIBRARY_PATH and load it.*/
bool loadLibrary(const std::string& fileName);
/** close the attached library with specified name.*/
bool closeLibrary(const std::string& fileName);
osg::Object* readObjectOfType(const osg::Object& compObj,Input& fr);
osg::Object* readObject(Input& fr);
osg::Image* readImage(Input& fr);
osg::Drawable* readDrawable(Input& fr);
osg::StateAttribute* readStateAttribute(Input& fr);
osg::Node* readNode(Input& fr);
bool writeObject(const osg::Object& obj,Output& fw);
osg::Object* readObject(const std::string& fileName);
bool writeObject(const osg::Object& obj, const std::string& fileName);
osg::Image* readImage(const std::string& fileName);
bool writeImage(const osg::Image& obj, const std::string& fileName);
osg::Node* readNode(const std::string& fileName);
bool writeNode(const osg::Node& node, const std::string& fileName);
void setCreateNodeFromImage(bool flag) { _createNodeFromImage = flag; }
bool getCreateNodeFromImage() const { return _createNodeFromImage; }
private:
typedef std::map<std::string,osg::ref_ptr<DotOsgWrapper> > DotOsgWrapperMap;
typedef std::vector<osg::ref_ptr<ReaderWriter> > ReaderWriterList;
typedef std::vector<osg::ref_ptr<DynamicLibrary> > DynamicLibraryList;
typedef std::map<std::string,std::string> ExtensionAliasMap;
/** constructor is private, as its a singleton, preventing
construction other than via the instance() method and
therefore ensuring only one copy is ever constructed*/
Registry();
/** get the attached library with specified name.*/
DynamicLibraryList::iterator getLibraryItr(const std::string& fileName);
DynamicLibrary* getLibrary(const std::string& fileName);
bool _createNodeFromImage;
osg::Object* readObject(DotOsgWrapperMap& dowMap,Input& fr);
DotOsgWrapperMap _objectWrapperMap;
DotOsgWrapperMap _imageWrapperMap;
DotOsgWrapperMap _drawableWrapperMap;
DotOsgWrapperMap _stateAttrWrapperMap;
DotOsgWrapperMap _nodeWrapperMap;
DotOsgWrapperMap _classNameWrapperMap;
ReaderWriterList _rwList;
DynamicLibraryList _dlList;
bool _openingLibrary;
// map to alias to extensions to plugins.
ExtensionAliasMap _extAliasMap;
};
/** Proxy class for automatic registration of DotOsgWrappers with the Registry.*/
class RegisterDotOsgWrapperProxy
{
public:
RegisterDotOsgWrapperProxy(osg::Object* proto,
const std::string& name,
const std::string& associates,
DotOsgWrapper::ReadFunc readFunc,
DotOsgWrapper::WriteFunc writeFunc,
DotOsgWrapper::ReadWriteMode readWriteMode=DotOsgWrapper::READ_AND_WRITE)
{
if (Registry::instance())
{
_wrapper = new DotOsgWrapper(proto,name,associates,readFunc,writeFunc,readWriteMode);
Registry::instance()->addDotOsgWrapper(_wrapper.get());
}
}
~RegisterDotOsgWrapperProxy()
{
if (Registry::instance())
{
Registry::instance()->removeDotOsgWrapper(_wrapper.get());
}
}
protected:
osg::ref_ptr<DotOsgWrapper> _wrapper;
};
/** Proxy class for automatic registration of reader/writers with the Registry.*/
template<class T>
class RegisterReaderWriterProxy
{
public:
RegisterReaderWriterProxy()
{
if (Registry::instance())
{
_rw = new T;
Registry::instance()->addReaderWriter(_rw.get());
}
}
~RegisterReaderWriterProxy()
{
if (Registry::instance())
{
Registry::instance()->removeReaderWriter(_rw.get());
}
}
protected:
osg::ref_ptr<T> _rw;
};
};
#endif

33
include/osgDB/Version Normal file
View File

@@ -0,0 +1,33 @@
#ifndef OSG_VERSION
#define OSG_VERSION 1
#include <osgDB/Export>
extern "C" {
/**
* osgDBGetVersion() returns the library version number.
* Numbering conventon : osg_src-0.8.31 will return 0.8.31 from getVersion_osg.
*
* This C function can be also used to check for the existance of the OpenSceneGraph
* library using autoconf and its m4 macro AC_CHECK_LIB.
*
* Here is the code to add to your configure.in:
\verbatim
#
# Check for the OpenSceneGraph (OSG) library
#
AC_CHECK_LIB(osg, osgDBGetVersion, ,
[AC_MSG_ERROR(OpenSceneGraph DB library not found. See http://www.openscenegraph.org)],)
\endverbatim
*/
extern OSGDB_EXPORT const char* osgDBGetVersion();
/**
* getLibraryName() returns the library name in human friendly form.
*/
extern OSGDB_EXPORT const char* osgDBGetLibraryName();
};
#endif

41
include/osgDB/WriteFile Normal file
View File

@@ -0,0 +1,41 @@
#ifndef OSGDB_FILEUTILS
#define OSGDB_FILEUTILS 1
#include <osg/Image>
#include <osg/Node>
#include <osgDB/Export>
#include <string>
namespace osgDB {
/** Write an osg::Object to file.
* Return true on sucess,
* return false on failure.
* The osgDB::Registry is used to load the appropriate ReaderWriter plugin
* for the filename extension, and this plugin then handles the request
* to write the specified file.*/
OSGDB_EXPORT extern bool writeObjectFile(const osg::Object& object, const std::string& filename);
/** Write an osg::Image to file.
* Return true on sucess,
* return false on failure.
* The osgDB::Registry is used to load the appropriate ReaderWriter plugin
* for the filename extension, and this plugin then handles the request
* to write the specified file.*/
OSGDB_EXPORT extern bool writeImageFile(const osg::Image& image, const std::string& filename);
/** Write an osg::Node to file.
* Return true on sucess,
* return false on failure.
* The osgDB::Registry is used to load the appropriate ReaderWriter plugin
* for the filename extension, and this plugin then handles the request
* to write the specified file.*/
OSGDB_EXPORT extern bool writeNodeFile(const osg::Node& node, const std::string& filename);
};
#endif

View File

@@ -7,8 +7,8 @@
extern "C" {
/**
* getVersion_osgGLUT() returns the library version number.
* Numbering conventon : osg_src-0.8-31 will return 0.8.31 from getVersion_osgGLUT.
* osgGLUTGetVersion() returns the library version number.
* Numbering conventon : osg_src-0.8.31 will return 0.8.31.
*
* This C function can be also used to check for the existance of the OpenSceneGraph
* library using autoconf and its m4 macro AC_CHECK_LIB.

View File

@@ -1,12 +1,7 @@
#ifndef OSGGLUT_VIEWER
#define OSGGLUT_VIEWER 1
#include <osg/OSG>
#include <osg/GeoState>
#include <osg/Scene>
#include <osg/Light>
#include <osg/DCS>
#include <osg/GL>
#include <osg/NodeVisitor>
#include <osg/Geode>
#include <osg/Timer>
@@ -33,9 +28,9 @@ using namespace std;
namespace osgGLUT{
/** A basic viewer base class which provides a window, simple keyboard and mouse interaction.
* Please note, this viewer class has been developed via a rather haphazzard
* path and *needs* a total rewrite. It currently surfices for osg demo's
* but shouldn't be viewed as the be all or end of osg viewer classes.
* Please note, this viewer class has been developed via a rather haphazard
* path and <i>needs</i> a total rewrite. It currently suffices for osg demo's
* but shouldn't be viewed as the be all and end of osg viewer classes.
* Someone please rewrite it :-)
*/
class OSGGLUT_EXPORT Viewer : public osgUtil::GUIActionAdapter
@@ -45,14 +40,34 @@ class OSGGLUT_EXPORT Viewer : public osgUtil::GUIActionAdapter
Viewer();
virtual ~Viewer();
virtual bool init( osg::Node* );
void setWindowOrigin(int x, int y) { wx = x, wy = y; };
void setWindowSize(int width, int height) { ww = width, wh = height; };
void setWindowTitle(const std::string& title) { _title = title; }
/** init is deprecated, you should use addViewport instead. init is
* only available for backwards compatibility.*/
virtual void init(osg::Node* rootnode);
virtual void addViewport(osgUtil::SceneView* sv,
float x = 0.0, float y = 0.0,
float width = 1.0, float height = 1.0);
virtual void addViewport(osg::Node*,
float x = 0.0, float y = 0.0,
float width = 1.0, float height = 1.0);
const int getNumViewports() const { return _viewportList.size(); }
osgUtil::SceneView* getViewportSceneView(unsigned int pos)
{ return _viewportList[pos].sceneView.get(); }
virtual bool open();
virtual bool run();
// called on each frame redraw..
virtual bool update();
virtual bool traverse();
virtual bool draw();
// called on each frame redraw..return the time in ms for each operation.
virtual float app(unsigned int viewport);
virtual float cull(unsigned int viewport);
virtual float draw(unsigned int viewport);
// initialize the clock.
long initClock();
@@ -69,18 +84,20 @@ class OSGGLUT_EXPORT Viewer : public osgUtil::GUIActionAdapter
void help(ostream& fout);
// hande multiple camera.
void registerCameraManipulator(osgUtil::CameraManipulator* cm);
void selectCameraManipulator(unsigned int pos);
unsigned int registerCameraManipulator(osgUtil::CameraManipulator* cm,
unsigned int viewport = 0);
void selectCameraManipulator(unsigned int pos,
unsigned int viewport = 0);
// derived from osgUtil::GUIActionAdapter
virtual void needRedraw(bool /*needed*/) {} // redraw always done.
virtual void needContinuousUpdate(bool /*needed*/) {} // continous update always
virtual void needWarpPointer(int x,int y);
virtual void requestRedraw() {} // redraw always by iddle callback done.
virtual void requestContinuousUpdate(bool /*needed*/) {} // continous update always
virtual void requestWarpPointer(int x,int y);
protected:
static void displayCB();
static void reshapeCB(GLint w, GLint h);
static void reshapeCB(int w, int h);
static void visibilityCB(int state);
static void mouseMotionCB(int x, int y);
static void mousePassiveMotionCB(int x, int y);
@@ -94,25 +111,39 @@ class OSGGLUT_EXPORT Viewer : public osgUtil::GUIActionAdapter
virtual void mousePassiveMotion(int x, int y);
virtual void mouse(int button, int state, int x, int y);
virtual void keyboard(unsigned char key, int x, int y);
void setFocusedViewport(unsigned int pos);
int mapWindowXYToSceneView(int x, int y);
void showStats(void);
static Viewer* s_theViewer;
osg::ref_ptr<osgUtil::SceneView> _sceneView;
typedef std::vector<osg::ref_ptr<osgUtil::CameraManipulator> > CameraManipList;
osg::ref_ptr<osgUtil::CameraManipulator> _cameraManipulator;
CameraManipList _cameraManipList;
struct ViewportDef
{
osg::ref_ptr<osgUtil::SceneView> sceneView;
float viewport[4]; // Win-size-relative [0,1]
osg::ref_ptr<osgUtil::CameraManipulator> _cameraManipulator;
CameraManipList _cameraManipList;
};
typedef std::vector<ViewportDef> ViewportList;
ViewportList _viewportList;
unsigned int _focusedViewport;
std::string _saveFileName;
int ww, wh;
std::string _title;
int wx, wy, ww, wh;
int _is_open;
#ifdef SGV_USE_RTFS
unsigned int frame_rate;
RTfs *fs;
#endif
unsigned int frame_rate;
RTfs *fs;
#endif
bool _viewFrustumCullingActive;
bool _smallFeatureCullingActive;
@@ -125,8 +156,13 @@ class OSGGLUT_EXPORT Viewer : public osgUtil::GUIActionAdapter
int flat_shade;
int _two_sided_lighting;
bool fullscreen;
int _saved_ww,_saved_wh;
bool _printStats;
int _saved_wx, _saved_wy, _saved_ww,_saved_wh;
float frRate; // gwm Jul 2001 added convolved ('averaged') frame rate
int _printStats; // gwm Jul 2001 change from bool
struct { // gwm Jul 2001, added for display of statistics
float timeApp, timeCull, timeDraw, timeFrame;
osg::Timer_t frameend;
} times[3]; // store up to 3 frames worth of times
bool _useDisplayLists;
osg::Timer _timer;

View File

@@ -1,15 +1,17 @@
#ifndef OSGUTIL_CAMERAMANIPULATOR
#define OSGUTIL_CAMERAMANIPULATOR 1
#include <osg/Referenced>
#include <osg/Camera>
#include <osg/Node>
#include <osgUtil/Export>
#include <osgUtil/GUIEventHandler>
#include <osgUtil/GUIEventAdapter>
#include <osgUtil/GUIActionAdapter>
namespace osgUtil{
class OSGUTIL_EXPORT CameraManipulator : public osg::Referenced
class OSGUTIL_EXPORT CameraManipulator : public GUIEventHandler
{
public:
@@ -20,7 +22,7 @@ class OSGUTIL_EXPORT CameraManipulator : public osg::Referenced
virtual void setCamera(osg::Camera*);
/** get the attached a camera.*/
virtual osg::Camera * getCamera() const;
virtual const osg::Camera * getCamera() const;
/** Attach a node to the manipulator.
Automatically detaches previously attached node.
@@ -29,17 +31,17 @@ class OSGUTIL_EXPORT CameraManipulator : public osg::Referenced
virtual void setNode(osg::Node*) {}
/** Return node if attached.*/
virtual osg::Node* getNode() const { return NULL; }
virtual const osg::Node* getNode() const { return NULL; }
/** Move the camera to the default position.
May be ignored by manipulators if home functionality is not appropriate.*/
virtual void home(GUIEventAdapter& ,GUIActionAdapter&) {}
virtual void home(const GUIEventAdapter& ,GUIActionAdapter&) {}
/** Start/restart the manipulator.*/
virtual void init(GUIEventAdapter& ,GUIActionAdapter&) {}
virtual void init(const GUIEventAdapter& ,GUIActionAdapter&) {}
/** Handle events, return true if handled, false otherwise.*/
virtual bool update(GUIEventAdapter& ea,GUIActionAdapter& us);
virtual bool handle(const GUIEventAdapter& ea,GUIActionAdapter& us);
protected:

View File

@@ -1,15 +1,17 @@
#ifndef OSGUTIL_COMPILEGEOSETVISITOR
#define OSGUTIL_COMPILEGEOSETVISITOR 1
#ifndef OSGUTIL_DISPLAYLISTVISITOR
#define OSGUTIL_DISPLAYLISTVISITOR 1
#include <osg/NodeVisitor>
#include <osg/Geode>
#include <osg/State>
#include <osgUtil/Export>
namespace osgUtil {
/** Visitor for traversing scene set each osg::GeoSet's _useDisplayList flag, or
* immediately compiling osg::GeoSet's OpenGL Display lists. The mode of operation
/** Visitor for traversing scene graph and setting each osg::GeoSet's _useDisplayList flag,
* with option to immediately compile osg::GeoSet's OpenGL Display lists.
* The mode of operation
* of the vistor is controlled by setting the DisplayListMode either on visitor
* constructor or via the setDisplayListMode() method. DisplayListMode options are:
* _displayListMode == SWITCH_ON_AND_COMPILE_DISPLAY_LISTS cals gset->compile() on
@@ -33,6 +35,7 @@ class OSGUTIL_EXPORT DisplayListVisitor : public osg::NodeVisitor
enum DisplayListMode
{
SWITCH_ON_AND_COMPILE_DISPLAY_LISTS,
COMPILE_ON_DISPLAY_LISTS,
SWITCH_ON_DISPLAY_LISTS,
SWITCH_OFF_DISPLAY_LISTS
};
@@ -48,6 +51,20 @@ class OSGUTIL_EXPORT DisplayListVisitor : public osg::NodeVisitor
/** Get the operational mode.*/
DisplayListMode getDisplayListMode() const { return _displayListMode; }
/** Set the State to use during traversal. */
void setState(osg::State* state)
{
_externalState = state;
if (_externalState.valid()) _activeState = _externalState;
else _activeState = _localState;
}
osg::State* getState()
{
return _activeState.get();
}
/** Simply traverse using standard NodeVisitor traverse method.*/
virtual void apply(osg::Node& node)
@@ -63,6 +80,13 @@ class OSGUTIL_EXPORT DisplayListVisitor : public osg::NodeVisitor
protected:
DisplayListMode _displayListMode;
/** local state is created in constructor and used as the default state during traversal.*/
osg::ref_ptr<osg::State> _localState;
/** external state is used to override the default state.*/
osg::ref_ptr<osg::State> _externalState;
/** active state is equal to _externalState when it is valid, otherwise defaults to _localState.*/
osg::ref_ptr<osg::State> _activeState;
};

View File

@@ -19,32 +19,32 @@ class OSGUTIL_EXPORT DriveManipulator : public CameraManipulator
virtual void setNode(osg::Node*);
/** Return node if attached.*/
virtual osg::Node* getNode() const;
virtual const osg::Node* getNode() const;
/** Move the camera to the default position.
May be ignored by manipulators if home functionality is not appropriate.*/
virtual void home(GUIEventAdapter& ea,GUIActionAdapter& us);
virtual void home(const GUIEventAdapter& ea,GUIActionAdapter& us);
/** Start/restart the manipulator.*/
virtual void init(GUIEventAdapter& ea,GUIActionAdapter& us);
virtual void init(const GUIEventAdapter& ea,GUIActionAdapter& us);
/** handle events, return true if handled, false otherwise.*/
virtual bool update(GUIEventAdapter& ea,GUIActionAdapter& us);
virtual bool handle(const GUIEventAdapter& ea,GUIActionAdapter& us);
private:
/** Reset the internal GUIEvent stack.*/
void flushMouseEventStack();
/** Add the current mouse GUIEvent to internal stack.*/
void addMouseEvent(GUIEventAdapter& ea);
void addMouseEvent(const GUIEventAdapter& ea);
/** For the give mouse movement calculate the movement of the camera.
Return true is camera has moved and a redraw is required.*/
bool calcMovement();
// Internal event stack comprising last three mouse events.
osg::ref_ptr<GUIEventAdapter> _ga_t1;
osg::ref_ptr<GUIEventAdapter> _ga_t0;
osg::ref_ptr<const GUIEventAdapter> _ga_t1;
osg::ref_ptr<const GUIEventAdapter> _ga_t0;
osg::ref_ptr<osg::Node> _node;

View File

@@ -19,17 +19,17 @@ class OSGUTIL_EXPORT FlightManipulator : public CameraManipulator
virtual void setNode(osg::Node*);
/** Return node if attached.*/
virtual osg::Node* getNode() const;
virtual const osg::Node* getNode() const;
/** Move the camera to the default position.
May be ignored by manipulators if home functionality is not appropriate.*/
virtual void home(GUIEventAdapter& ea,GUIActionAdapter& us);
virtual void home(const GUIEventAdapter& ea,GUIActionAdapter& us);
/** Start/restart the manipulator.*/
virtual void init(GUIEventAdapter& ea,GUIActionAdapter& us);
virtual void init(const GUIEventAdapter& ea,GUIActionAdapter& us);
/** handle events, return true if handled, false otherwise.*/
virtual bool update(GUIEventAdapter& ea,GUIActionAdapter& us);
virtual bool handle(const GUIEventAdapter& ea,GUIActionAdapter& us);
enum YawControlMode {
YAW_AUTOMATICALLY_WHEN_BANKED,
@@ -44,15 +44,15 @@ class OSGUTIL_EXPORT FlightManipulator : public CameraManipulator
/** Reset the internal GUIEvent stack.*/
void flushMouseEventStack();
/** Add the current mouse GUIEvent to internal stack.*/
void addMouseEvent(GUIEventAdapter& ea);
void addMouseEvent(const GUIEventAdapter& ea);
/** For the give mouse movement calculate the movement of the camera.
Return true is camera has moved and a redraw is required.*/
bool calcMovement();
// Internal event stack comprising last three mouse events.
osg::ref_ptr<GUIEventAdapter> _ga_t1;
osg::ref_ptr<GUIEventAdapter> _ga_t0;
osg::ref_ptr<const GUIEventAdapter> _ga_t1;
osg::ref_ptr<const GUIEventAdapter> _ga_t0;
osg::ref_ptr<osg::Node> _node;

View File

@@ -6,14 +6,42 @@
namespace osgUtil{
/** Pure virtual base class for adapting the GUI actions for use in CameraManipulators.*/
/** Pure virtual base class for adapting the GUI actions requested by CameraManipulators
* into actions which are handled by the GUI toolkit of the users application.
*
* There are several was of using the ActionAdapter either inheriting it as
* done with osgGLUT::Viewer class or passing a simple struct to the camera
* manipulator then unpacking the results and working out what to do to respond
* to the requests.
*
* Also there are several ways to run your app and handle the updating of
* the window. osgGLUT::Viewer always has a idle callback registered which does a
* redraw all the time. osgGLUT::Viewer can safely ignore both requestRedraw() and
* requestContinousUpdate() as these are happening all the time anyway.
*
* Other apps will probably want to respond to the requestRedraw() and
* requestContinousUpdate(bool) and again there is more than one way to handle it.
* You can override requestRedraw() and implement to call your own window
* redraw straight away. Or you can implement so that a flag is set and
* then you then respond the flag being set in your own leisure.
*
* requestContinousUpdate(bool) is for enabling a throw or idle
* callback to be requested by the camera manipulator. Again you can respond
* to this immediately by registering a idle callback or a timed callback, or
* you can delay setting the callback and do at you own leisure.
*
* requestWarpPointer(int,int) is requesting a respositioning of a mouse pointer
* to a specified x,y location on the window. Used by some camera manipulators
* to initialize the mouse pointer when mouse position relative to a controls
* neutral mouse position is required, i.e when mimicking a aircrafts joystick.
*/
class GUIActionAdapter
{
public:
virtual void needRedraw(bool needed=true) = 0;
virtual void needContinuousUpdate(bool needed=true) = 0;
virtual void needWarpPointer(int x,int y) = 0;
virtual void requestRedraw() = 0;
virtual void requestContinuousUpdate(bool needed=true) = 0;
virtual void requestWarpPointer(int x,int y) = 0;
};

View File

@@ -7,8 +7,13 @@
namespace osgUtil{
/** Pure virtual base class for adapting platform specfic events into
generic keyboard and mouse events. */
/** Pure virtual base class for adapting platform specific events into
* generic keyboard and mouse events.
*
* Used as GUI toolkit independent input into the osgUtil::CameraManipualor's.
* For an example of how GUIEventAdapter is specialised for a particular GUI
* Toolkit see osgGLUT::GLUTEventAdapter.
*/
class GUIEventAdapter : public osg::Referenced
{
public:
@@ -36,7 +41,7 @@ class GUIEventAdapter : public osg::Referenced
/** Get the EventType of the GUI event.*/
virtual EventType getEventType() const = 0;
/** key pressed, return -1 if inapropriate for this event. */
/** key pressed, return -1 if inappropriate for this event. */
virtual int getKey() const = 0;
/** button pressed/released, return -1 if inappropriate for this event.*/
@@ -69,7 +74,7 @@ class GUIEventAdapter : public osg::Referenced
protected:
/** Force users to create on heap, so that mulitple referencing is safe.*/
/** Force users to create on heap, so that multiple referencing is safe.*/
virtual ~GUIEventAdapter() {}
};

View File

@@ -2,8 +2,9 @@
#define OSGUTIL_INTERSECTVISITOR 1
#include <osg/NodeVisitor>
#include <osg/Seg>
#include <osg/LineSegment>
#include <osg/Geode>
#include <osg/GeoSet>
#include <osg/Matrix>
#include <osgUtil/Export>
@@ -23,15 +24,15 @@ class OSGUTIL_EXPORT IntersectState : public osg::Referenced
osg::Matrix* _matrix;
osg::Matrix* _inverse;
typedef std::vector< std::pair<osg::Seg*,osg::Seg*> > SegList;
SegList _segList;
typedef std::vector< std::pair<osg::LineSegment*,osg::LineSegment*> > LineSegmentList;
LineSegmentList _segList;
typedef unsigned int SegmentMask;
typedef std::vector<SegmentMask> SegmentMaskStack;
SegmentMaskStack _segmentMaskStack;
typedef unsigned int LineSegmentmentMask;
typedef std::vector<LineSegmentmentMask> LineSegmentmentMaskStack;
LineSegmentmentMaskStack _segmentMaskStack;
bool isCulled(const osg::BoundingSphere& bs,SegmentMask& segMaskOut);
bool isCulled(const osg::BoundingBox& bb,SegmentMask& segMaskOut);
bool isCulled(const osg::BoundingSphere& bs,LineSegmentmentMask& segMaskOut);
bool isCulled(const osg::BoundingBox& bb,LineSegmentmentMask& segMaskOut);
protected:
@@ -52,14 +53,14 @@ class OSGUTIL_EXPORT Hit : public osg::Referenced
bool operator < (const Hit& hit) const
{
if (_originalSeg<hit._originalSeg) return true;
if (_originalSeg>hit._originalSeg) return false;
if (_originalLineSegment<hit._originalLineSegment) return true;
if (_originalLineSegment>hit._originalLineSegment) return false;
return _ratio<hit._ratio;
}
float _ratio;
osg::Seg* _originalSeg;
osg::Seg* _localSeg;
osg::LineSegment* _originalLineSegment;
osg::LineSegment* _localLineSegment;
osg::NodePath _nodePath;
osg::Geode* _geode;
osg::GeoSet* _geoset;
@@ -85,7 +86,7 @@ class OSGUTIL_EXPORT IntersectVisitor : public osg::NodeVisitor
void reset();
/** Add a line segment to use for intersection testing during scene traversal.*/
void addSeg(osg::Seg* seg);
void addLineSegment(osg::LineSegment* seg);
/** Modes to control how IntersectVisitor reports hits. */
enum HitReportingMode {
@@ -100,9 +101,9 @@ class OSGUTIL_EXPORT IntersectVisitor : public osg::NodeVisitor
//typedef std::multiset<Hit> HitList;
typedef std::vector<Hit> HitList;
typedef std::map<osg::Seg*,HitList > SegHitListMap;
HitList& getHitList(osg::Seg* seg) { return _segHitList[seg]; }
int getNumHits(osg::Seg* seg) { return _segHitList[seg].size(); }
typedef std::map<osg::LineSegment*,HitList > LineSegmentHitListMap;
HitList& getHitList(osg::LineSegment* seg) { return _segHitList[seg]; }
int getNumHits(osg::LineSegment* seg) { return _segHitList[seg].size(); }
bool hits();
@@ -111,10 +112,9 @@ class OSGUTIL_EXPORT IntersectVisitor : public osg::NodeVisitor
virtual void apply(osg::Billboard& node);
virtual void apply(osg::Group& node);
virtual void apply(osg::DCS& node);
virtual void apply(osg::Transform& node);
virtual void apply(osg::Switch& node);
virtual void apply(osg::LOD& node);
virtual void apply(osg::Scene& node);
protected:
@@ -127,13 +127,13 @@ class OSGUTIL_EXPORT IntersectVisitor : public osg::NodeVisitor
bool enterNode(osg::Node& node);
void leaveNode();
typedef std::vector<IntersectState*> IntersectStateStack;
typedef std::vector<osg::ref_ptr<IntersectState> > IntersectStateStack;
IntersectStateStack _intersectStateStack;
osg::NodePath _nodePath;
osg::NodePath _nodePath;
HitReportingMode _hitReportingMode;
SegHitListMap _segHitList;
LineSegmentHitListMap _segHitList;
};
};

View File

@@ -2,13 +2,11 @@
#define OSGUTIL_SCENEVIEW 1
#include <osg/Node>
#include <osg/GeoState>
#include <osg/StateSet>
#include <osg/Light>
#include <osg/Camera>
#include <osgUtil/RenderVisitor>
#include <osgUtil/Export>
#include <osgUtil/CullVisitor>
namespace osgUtil {
@@ -33,6 +31,11 @@ class OSGUTIL_EXPORT SceneView : public osg::Referenced
*/
osg::Node* getSceneData() { return _sceneData.get(); }
/** Get the const scene data which to view. The data will typically be
* an osg::Scene but can be any osg::Node type.
*/
const osg::Node* getSceneData() const { return _sceneData.get(); }
/** Set the viewport of the scene view. */
void setViewport(int x,int y,int width,int height)
{
@@ -62,8 +65,9 @@ class OSGUTIL_EXPORT SceneView : public osg::Referenced
/** Get the background color.*/
const osg::Vec4& getBackgroundColor() const { return _backgroundColor; }
void setGlobalState(osg::GeoState* state) { _globalState = state; }
osg::GeoState* getGlobalState() const { return _globalState.get(); }
void setGlobalState(osg::StateSet* state) { _globalState = state; }
osg::StateSet* getGlobalState() { return _globalState.get(); }
const osg::StateSet* getGlobalState() const { return _globalState.get(); }
enum LightingMode {
HEADLIGHT, // default
@@ -75,13 +79,33 @@ class OSGUTIL_EXPORT SceneView : public osg::Referenced
LightingMode getLightingMode() const { return _lightingMode; }
void setLight(osg::Light* light) { _light = light; }
osg::Light* getLight() const { return _light.get(); }
osg::Light* getLight() { return _light.get(); }
const osg::Light* getLight() const { return _light.get(); }
void setCamera(osg::Camera* camera) { _camera = camera; }
osg::Camera* getCamera() const { return _camera.get(); }
osg::Camera* getCamera() { return _camera.get(); }
const osg::Camera* getCamera() const { return _camera.get(); }
void setRenderVisitor(osgUtil::RenderVisitor* rv) { _renderVisitor = rv; }
osgUtil::RenderVisitor* getRenderVisitor() const { return _renderVisitor.get(); }
void setState(osg::State* state) { _state = state; }
osg::State* getState() { return _state.get(); }
const osg::State* getState() const { return _state.get(); }
void setAppVisitor(osg::NodeVisitor* av) { _appVisitor = av; }
osg::NodeVisitor* getAppVisitor() { return _appVisitor.get(); }
const osg::NodeVisitor* getAppVisitor() const { return _appVisitor.get(); }
void setCullVisitor(osgUtil::CullVisitor* cv) { _cullVisitor = cv; }
osgUtil::CullVisitor* getCullVisitor() { return _cullVisitor.get(); }
const osgUtil::CullVisitor* getCullVisitor() const { return _cullVisitor.get(); }
void setRenderGraph(osgUtil::RenderGraph* rg) { _rendergraph = rg; }
osgUtil::RenderGraph* getRenderGraph() { return _rendergraph.get(); }
const osgUtil::RenderGraph* getRenderGraph() const { return _rendergraph.get(); }
void setRenderStage(osgUtil::RenderStage* rs) { _renderStage = rs; }
osgUtil::RenderStage* getRenderStage() { return _renderStage.get(); }
const osgUtil::RenderStage* getRenderStage() const { return _renderStage.get(); }
void setLODBias(float bias) { _lodBias = bias; }
float getLODBias() const { return _lodBias; }
@@ -94,7 +118,14 @@ class OSGUTIL_EXPORT SceneView : public osg::Referenced
/** return true if SceneView automatically caclculates near and
far clipping planes for each frame.
*/
bool getCalcNearFar() { return _calc_nearfar; }
bool getCalcNearFar() const { return _calc_nearfar; }
/** set whether the draw method should call renderer->prioritizeTexture.*/
void setPrioritizeTextures(bool pt) { _prioritizeTextures = pt; }
/** get whether the draw method should call renderer->prioritizeTexture.*/
bool getPrioritizeTextures() const { return _prioritizeTextures; }
/** Calculate, via glUnProject, the object coordinates of a window point.
Note, current implementation requires that SceneView::draw() has been previously called
@@ -124,7 +155,13 @@ class OSGUTIL_EXPORT SceneView : public osg::Referenced
bool projectObjectIntoWindow(const osg::Vec3& object,osg::Vec3& window) const;
/** do app traversal of attached scene graph using App NodeVisitor.*/
virtual void app();
/** do cull traversal of attached scene graph using App CullVisitor.*/
virtual void cull();
/** do draw traversal of draw bins generated by cull traversal.*/
virtual void draw();
protected:
@@ -132,11 +169,17 @@ class OSGUTIL_EXPORT SceneView : public osg::Referenced
virtual ~SceneView();
osg::ref_ptr<osg::Node> _sceneData;
osg::ref_ptr<osg::GeoState> _globalState;
osg::ref_ptr<osg::StateSet> _globalState;
osg::ref_ptr<osg::Light> _light;
osg::ref_ptr<osg::Camera> _camera;
osg::ref_ptr<osgUtil::RenderVisitor> _renderVisitor;
osg::ref_ptr<osg::State> _state;
osg::ref_ptr<osg::NodeVisitor> _appVisitor;
osg::ref_ptr<osgUtil::CullVisitor> _cullVisitor;
osg::ref_ptr<osgUtil::RenderGraph> _rendergraph;
osg::ref_ptr<osgUtil::RenderStage> _renderStage;
bool _need_compile;
bool _calc_nearfar;
@@ -150,13 +193,11 @@ class OSGUTIL_EXPORT SceneView : public osg::Referenced
// viewport x,y,width,height respectiveyly.
GLint _view[4];
// model and project matices, used by glUnproject to get
// to generate rays form the eyepoint through the mouse x,y.
GLdouble _model[16];
GLdouble _proj[16];
LightingMode _lightingMode;
bool _prioritizeTextures;
int _frameNumber;
};
};

View File

@@ -19,25 +19,25 @@ class OSGUTIL_EXPORT TrackballManipulator : public CameraManipulator
virtual void setNode(osg::Node*);
/** Return node if attached.*/
virtual osg::Node* getNode() const;
virtual const osg::Node* getNode() const;
/** Move the camera to the default position.
May be ignored by manipulators if home functionality is not appropriate.*/
virtual void home(GUIEventAdapter& ea,GUIActionAdapter& us);
virtual void home(const GUIEventAdapter& ea,GUIActionAdapter& us);
/** Start/restart the manipulator.*/
virtual void init(GUIEventAdapter& ea,GUIActionAdapter& us);
virtual void init(const GUIEventAdapter& ea,GUIActionAdapter& us);
/** handle events, return true if handled, false otherwise.*/
virtual bool update(GUIEventAdapter& ea,GUIActionAdapter& us);
virtual bool handle(const GUIEventAdapter& ea,GUIActionAdapter& us);
private:
/** Reset the internal GUIEvent stack.*/
void flushMouseEventStack();
/** Add the current mouse GUIEvent to internal stack.*/
void addMouseEvent(GUIEventAdapter& ea);
void addMouseEvent(const GUIEventAdapter& ea);
/** For the give mouse movement calculate the movement of the camera.
Return true is camera has moved and a redraw is required.*/
@@ -52,8 +52,8 @@ class OSGUTIL_EXPORT TrackballManipulator : public CameraManipulator
bool isMouseMoving();
// Internal event stack comprising last three mouse events.
osg::ref_ptr<GUIEventAdapter> _ga_t1;
osg::ref_ptr<GUIEventAdapter> _ga_t0;
osg::ref_ptr<const GUIEventAdapter> _ga_t1;
osg::ref_ptr<const GUIEventAdapter> _ga_t0;
osg::ref_ptr<osg::Node> _node;

22
include/osgWX/Export Normal file
View File

@@ -0,0 +1,22 @@
// The following symbole has a underscore suffix for compatibility.
#ifndef OSGWX_EXPORT_
#define OSGWX_EXPORT_ 1
#ifdef WIN32
#pragma warning( disable : 4251 )
#pragma warning( disable : 4275 )
#pragma warning( disable : 4786 )
#endif
#if defined(_MSC_VER)
# ifdef OSGWX_LIBRARY
# define OSGWX_EXPORT __declspec(dllexport)
# else
# define OSGWX_EXPORT __declspec(dllimport)
#endif /* OSGWX_LIBRARY */
#else
#define OSGWX_EXPORT
#endif
#endif

35
include/osgWX/Version Normal file
View File

@@ -0,0 +1,35 @@
#ifndef OSGWX_VERSION
#define OSGWX_VERSION 1
#include <osgWX/Export>
extern "C" {
/**
* osgWXGetVersion() returns the library version number.
* Numbering conventon : osg_src-0.8.31 will return 0.8.31.
*
* This C function can be also used to check for the existance of the OpenSceneGraph
* library using autoconf and its m4 macro AC_CHECK_LIB.
*
* Here is the code to add to your configure.in:
\verbatim
#
# Check for the OpenSceneGraph (OSG) WX library
#
AC_CHECK_LIB(osg, osgWXGetVersion, ,
[AC_MSG_ERROR(OpenSceneGraph WX library not found. See http://www.openscenegraph.org)],)
\endverbatim
*/
extern OSGWX_EXPORT const char* osgWXGetVersion();
/**
* getLibraryName_osgWX() returns the library name in human friendly form.
*/
extern OSGWX_EXPORT const char* osgWXGetLibraryName();
};
#endif

View File

@@ -0,0 +1,106 @@
#ifndef OSGWX_WXEVENTADAPTER
#define OSGWX_WXEVENTADAPTER 1
#include <osgUtil/GUIEventAdapter>
#include <osgWX/Export>
namespace osgWX {
/** Class for adapting WX events so that they can be used as input to
osgUtil::CameraManipulators.*/
class OSGWX_EXPORT WXEventAdapter : public osgUtil::GUIEventAdapter
{
public:
WXEventAdapter();
virtual ~WXEventAdapter() {}
/** Get the EventType of the GUI event.*/
virtual EventType getEventType() const { return _eventType; }
/** key pressed, return -1 if inapropriate for this event. */
virtual int getKey() const { return _key; }
/** button pressed/released, return -1 if inappropriate for this event.*/
virtual int getButton() const { return _button; }
/** window minimum x. */
virtual int getXmin() const { return _Xmin; }
/** window maximum x. */
virtual int getXmax() const { return _Xmax; }
/** window minimum y. */
virtual int getYmin() const { return _Ymin; }
/** window maximum y. */
virtual int getYmax() const { return _Ymax; }
/** current mouse x position.*/
virtual int getX() const { return _mx; }
/** current mouse y position.*/
virtual int getY() const { return _my; }
/** current mouse button state */
virtual unsigned int getButtonMask() const { return _buttonMask; }
/** time in seconds of event. */
virtual float time() const { return _time; }
/** static method for setting window dimensions.*/
static void setWindowSize(int Xmin, int Ymin, int Xmax, int Ymax);
/** static method for setting button state.*/
static void setButtonMask(unsigned int buttonMask);
/** method for adapting resize events. */
void adaptResize(float t, int Xmin, int Ymin, int Xmax, int Ymax);
/** method for adapting mouse motion events whilst mouse buttons are pressed.*/
void adaptMouseMotion(float t, int x, int y);
/** method for adapting mouse motion events whilst no mouse button are pressed.*/
void adaptMousePassiveMotion(float t,int x, int y);
/** method for adapting mouse button pressed/released events.*/
void adaptMouse(float t, class wxMouseEvent *event);
/** method for adapting keyboard events.*/
void adaptKeyboard(float t,unsigned char key, int x, int y );
/** method for adapting frame events, i.e. iddle/display callback.*/
void adaptFrame(float t);
void copyStaticVariables();
protected:
EventType _eventType;
int _key;
int _button;
int _Xmin,_Xmax;
int _Ymin,_Ymax;
int _mx;
int _my;
unsigned int _buttonMask;
float _time;
// used to accumulate the button mask state, it represents
// the current button mask state, which is modified by the
// adaptMouse() method which then copies it to value _buttonMask
// which required the mouse buttons state at the time of the event.
static unsigned int _s_accumulatedButtonMask;
// used to store window min and max values.
static int _s_Xmin;
static int _s_Xmax;
static int _s_Ymin;
static int _s_Ymax;
static int _s_mx;
static int _s_my;
};
} // namespace osgWX
#endif