Initial revision

This commit is contained in:
Don BURNS
2001-01-10 16:32:10 +00:00
parent 7c12eb9361
commit 70208ebc06
461 changed files with 70936 additions and 0 deletions

65
include/osg/AlphaFunc Normal file
View File

@@ -0,0 +1,65 @@
#ifndef OSG_ALPHAFUNC
#define OSG_ALPHAFUNC 1
#include <osg/Export>
#include <osg/Object>
#include <osg/GL>
namespace osg {
/** Encapsulte OpenGL glAlphaFunc.
*/
class SG_EXPORT AlphaFunc : public Object
{
public :
enum ComparisonFunction {
NEVER = GL_NEVER,
LESS = GL_LESS,
EQUAL = GL_EQUAL,
LEQUAL = GL_LEQUAL,
GREATER = GL_GREATER,
NOTEQUAL = GL_NOTEQUAL,
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)
{
_comparisonFunc = func;
_referenceValue = ref;
}
ComparisonFunction getFunction() const { return _comparisonFunc; }
float getRefrenceValue() const { return _referenceValue; }
static void enable();
static void disable();
void apply();
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;
};
};
#endif

84
include/osg/Billboard Normal file
View File

@@ -0,0 +1,84 @@
#ifndef OSG_BILLBOARD
#define OSG_BILLBOARD 1
#include <osg/Geode>
namespace osg {
/** Billboard - a Geode which orientates its child osg::GeoSet's to face
the eye point.
Typical uses are for trees, or particle explosions.
*/
class SG_EXPORT Billboard : public Geode
{
public:
enum Mode {
AXIAL_ROT,
POINT_ROT_EYE,
POINT_ROT_WORLD
};
Billboard();
virtual Object* clone() const { return new Billboard(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<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; }
void setMode(Mode mode) { _mode = mode; }
int getMode() const { return _mode; }
void setPos(int i,const Vec3& pos) { _positionList[i] = pos; }
void getPos(int i,Vec3& pos) const { pos = _positionList[i]; }
/** Add GeoSet 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 );
/** Add GeoSet 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);
/** Remove GeoSet 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 );
void calcRotation(const Vec3& eye_local, const Vec3& pos_local,Matrix& mat);
void calcTransform(const Vec3& eye_local, const Vec3& pos_local,Matrix& mat);
protected:
virtual ~Billboard();
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
virtual bool computeBound( void );
typedef std::vector<Vec3> PositionList;
Mode _mode;
Vec3 _axis;
PositionList _positionList;
};
};
#endif

116
include/osg/BoundingBox Normal file
View File

@@ -0,0 +1,116 @@
#ifndef OSG_BOUNDINGBOX
#define OSG_BOUNDINGBOX 1
#include <osg/Export>
#include <osg/Vec3>
#include <float.h>
namespace osg {
class BoundingSphere;
/** General purpose axis-aligned bounding box class for enclosing objects/vertices.
Used to bounding the leaf objects in the scene,
i.e. osg::GeoSet's to assist in view frustum culling etc.
*/
class SG_EXPORT BoundingBox
{
public:
/** The corner with the smallest values for each coordinate of the
bounding box.*/
Vec3 _min;
/** The corner with the largest values for each coordinate of the
bounding box.*/
Vec3 _max;
/** construct to invalid values to represent an unset bounding box.*/
BoundingBox() : _min(FLT_MAX,FLT_MAX,FLT_MAX),
_max(-FLT_MAX,-FLT_MAX,-FLT_MAX) {}
/** initialize to invalid values to represent an unset bounding box.*/
void init()
{
_min.set(FLT_MAX,FLT_MAX,FLT_MAX);
_max.set(-FLT_MAX,-FLT_MAX,-FLT_MAX);
}
/** return true if the bounding box contains valid values,
false if the bounding box is effectively unset/empty.*/
bool isValid() const
{
return _max.x()>=_min.x();
}
float& xMin() { return _min.x(); }
float xMin() const { return _min.x(); }
float& yMin() { return _min.y(); }
float yMin() const { return _min.y(); }
float& zMin() { return _min.z(); }
float zMin() const { return _min.z(); }
float& xMax() { return _max.x(); }
float xMax() const { return _max.x(); }
float& yMax() { return _max.y(); }
float yMax() const { return _max.y(); }
float& zMax() { return _max.z(); }
float zMax() const { return _max.z(); }
/** Calculate and return the center of the bounding box.*/
Vec3 center() const
{
return (_min+_max)*0.5f;
}
/** Calculate and return the radius of the bounding box.*/
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
{
return 0.25f*((_max-_min).length2());
}
/** return the corner of the bounding box.
Position (pos) is specfied by a number between 0 and 7,
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
{
return Vec3(pos&1?_max.x():_min.x(),pos&2?_max.y():_min.y(),pos&4?_max.z():_min.z());
}
/** If the vertex is outwith the box expand to ecompass vertex.
If this box is empty then move set this box's min max to vertex. */
void expandBy(const Vec3& v);
/** If incomming box is outwith the box expand to ecompass incomming box.
If this box is empty then move set this box to incomming box. */
void expandBy(const BoundingBox& bb);
/** If incomming sphere is outwith the box expand to ecompass incomming sphere.
If this box is empty then move set this box to encompass the sphere. */
void expandBy(const BoundingSphere& sh);
/** return true is vertex v is within the box.*/
bool contains(const Vec3& v)
{
return isValid() &&
(v.x()>=_min.x() && v.x()<=_max.x()) &&
(v.y()>=_min.y() && v.y()<=_max.y()) &&
(v.z()>=_min.z() && v.z()<=_max.z());
}
};
};
#endif

View File

@@ -0,0 +1,85 @@
#ifndef OSG_BOUNDINGSPHERE
#define OSG_BOUNDINGSPHERE 1
#include <osg/Export>
#include <osg/Vec3>
namespace osg {
/** General purpose bounding sphere class for enclosing nodes/objects/vertices.
Used to bound internal osg::Node's in the scene,
to assist in view frustrum culling etc. Similar in function to BoundingBox
but is quicker for evaluating culling, but generally encloses a greater volume
than a BoundingBox so will not cull so aggressively.
*/
class SG_EXPORT BoundingSphere
{
public:
Vec3 _center;
float _radius;
/** construct to invalid values to represent an unset bounding sphere.*/
BoundingSphere() : _center(0.0f,0.0f,0.0f),_radius(-1.0f) {}
/** initialize to invalid values to represent an unset bounding sphere.*/
void init()
{
_center.set(0.0f,0.0f,0.0f);
_radius = -1.0f;
}
/** return true if the bounding sphere contains valid values,
false if the bounding sphere is effectively unset.*/
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; }
/** return the const radius of the bounding sphere.*/
float radius() const { return _radius; }
/** return the radius of the bounding sphere.*/
float& radius() { 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; }
/** If the vertex is outwith the sphere expand to ecompass vertex.
Calculates the combination of movement of center and radius which
minimizes the radius increase. If this sphere is empty then
move the centrer to v and set radius to 0.*/
void expandBy(const Vec3& v);
/** If the vertex is outwith the sphere expand radius to ecompass vertex.
Unlike update, does not move the center, just increasing the radius.
If this sphere is empty then move the centrer to v and set radius to 0 */
void expandRadiusBy(const Vec3& v);
/** If incomming sphere is outwith the sphere expand to ecompass incomming sphere.
calculates the combination of movement of center and radius which
minimizes the radius increase. If this sphere is empty then
move the centrer to v and set radius to 0.*/
void expandBy(const BoundingSphere& sh);
/** If incomming sphere is outwith the sphere expand radius to ecompass incomming sphere.
Unlike update, does not move the center, just increasing the radius.
If this sphere is empty then move the centrer to v and set radius to 0. */
void expandRadiusBy(const BoundingSphere& sh);
/** return true is vertex v is within the sphere.*/
bool contains(const Vec3& v)
{
return isValid() && ((v-_center).length2()<=radius2());
}
};
};
#endif

140
include/osg/Camera Normal file
View File

@@ -0,0 +1,140 @@
#ifndef OSG_CAMERA
#define OSG_CAMERA 1
#include <osg/Export>
#include <osg/Scene>
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.
*/
class SG_EXPORT Camera: public osg::Referenced
{
public:
Camera();
virtual ~Camera();
/**
* 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; }
void setAspectRatio(double aspectRatio) { _aspectRatio = aspectRatio; }
double getAspectRatio() const { return _aspectRatio; }
/**
* hardwired home view for now, looking straight down the
* Z axis at the origin, with 'up' being the y axis.
*/
void home();
/**
* Set the View, the up vector should be orthogonal to the
* look vector.
*/
void setView(Vec3 eyePoint,
Vec3 lookPoint,
Vec3 upVector);
/** get the eyepoint. */
const Vec3& getEyePoint() const {return _eyePoint;}
/** get the lookpoint. */
const Vec3& getLookPoint() const {return _lookPoint;}
/** 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;
}
/** calculate look vector.*/
Vec3 getLookVector() const
{
Vec3 lv = (_lookPoint-_eyePoint);
lv.normalize();
return lv;
}
/** calculate focal distance.*/
float getFocalDistance() const
{
return (_lookPoint-_eyePoint).length();
}
/** 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;}
/** 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;
/** 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();
private:
// Disallow copy construction & assignment (for now)
Camera(const Camera&);
Camera& operator=(const Camera&);
Vec3 _eyePoint;
Vec3 _lookPoint;
Vec3 _upVector;
double _fovy;
double _aspectRatio;
double _nearPlane; // No Dougal, these are small... but those...
double _farPlane; // are far away
};
}
# endif

51
include/osg/CullFace Normal file
View File

@@ -0,0 +1,51 @@
#ifndef OSG_CULLFACE
#define OSG_CULLFACE 1
#include <osg/Export>
#include <osg/Object>
#include <osg/GL>
namespace osg {
/** Class to globally enable/disable OpenGL's polygon culling mode
(GL_CULL_FACE).
*/
class SG_EXPORT CullFace : public Object
{
public :
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();
void apply();
protected:
virtual ~CullFace();
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
Mode _mode;
};
};
#endif

45
include/osg/DCS Normal file
View File

@@ -0,0 +1,45 @@
#ifndef OSG_DCS
#define OSG_DCS 1
#include <osg/Group>
#include <osg/Matrix>
namespace osg {
/** DCS - Dynamic Coordinate System a is group which all children
are transformed by the the DCS's osg::Matrix. Typical uses
of the DCS is for positioning objects within a scene or
producing trakerball functionality.
*/
class SG_EXPORT DCS : public Group
{
public :
DCS();
DCS(const Matrix& matix);
virtual Object* clone() const { return new DCS(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<DCS*>(obj)!=NULL; }
virtual const char* className() const { return "DCS"; }
virtual void accept(NodeVisitor& nv) { nv.apply(*this); }
void setMatrix(const Matrix& mat );
Matrix* getMatrix() { return _mat; }
void preTranslate( float tx, float ty, float tz );
void preRotate( float deg, float x, float y, float z );
bool computeBound();
protected :
virtual ~DCS();
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
Matrix *_mat;
};
};
#endif

View File

@@ -0,0 +1,51 @@
#ifndef OSG_DYNAMICLIBRARY
#define OSG_DYNAMICLIBRARY 1
#include <string>
#include <osg/Referenced>
#ifdef WIN32
//#include <Windows.h>
#endif
namespace osg {
/** DynamicLibrary - encapsulates the loading and unloading of dynamic libraries,
typically used for loading ReaderWriter plug-ins.
*/
class SG_EXPORT DynamicLibrary : public Referenced
{
public:
#ifdef WIN32
// from Snados.h
typedef void* HANDLE;
// from Delayimp.h
typedef void* PROC_ADDRESS;
#else
typedef void* HANDLE;
typedef void* PROC_ADDRESS;
#endif
static DynamicLibrary* loadLibrary(const std::string& libraryName);
const std::string& getName() const { return _name; }
const std::string& getFullName() const { return _fullName; }
HANDLE getHandle() const { return _handle; }
PROC_ADDRESS getProcAddress(const std::string& procName);
protected:
DynamicLibrary(const std::string& name,HANDLE handle);
~DynamicLibrary();
HANDLE _handle;
std::string _name;
std::string _fullName;
};
};
#endif // __DYNAMIC_LIBRARY_H

32
include/osg/Export Normal file
View File

@@ -0,0 +1,32 @@
#ifndef OSG_EXPORT
#define OSG_EXPORT 1
#ifdef WIN32
#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)
# ifdef SG_LIBRARY
# define SG_EXPORT __declspec(dllexport)
# else
# define SG_EXPORT __declspec(dllimport)
# endif /* SG_LIBRARY */
#else
# define SG_EXPORT
#endif
#endif

View File

@@ -0,0 +1,15 @@
#ifndef OSG_EXTENSIONSUPPORTED
#define OSG_EXTENSIONSUPPORTED 1
#include <osg/Export>
namespace osg {
/** return true if OpenGL "extension" is supported.
note: Must only called within a valid OpenGL context,
undefined behaviour may occur otherwise.*/
SG_EXPORT extern bool ExtensionSupported(const char *extension);
};
#endif

100
include/osg/Field Normal file
View File

@@ -0,0 +1,100 @@
#ifndef OSG_FIELD
#define OSG_FIELD 1
#include <osg/Export>
#include <string>
#include <stdlib.h>
namespace osg {
class SG_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 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

62
include/osg/FieldReader Normal file
View File

@@ -0,0 +1,62 @@
#ifndef OSG_FIELDREADER
#define OSG_FIELDREADER 1
#include <osg/Export>
#include <string.h>
#include <stdlib.h>
#ifdef OSG_USE_IO_DOT_H
#include <iostream.h>
#else
#include <iostream>
using namespace std;
#endif
namespace osg {
class Field;
class SG_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 _delimatorEatLookUp[256];
bool _delimatorKeepLookUp[256];
};
};
#endif // __SG_FIELD_READER_H

View File

@@ -0,0 +1,68 @@
#ifndef OSG_FIELDREADERITERATOR
#define OSG_FIELDREADERITERATOR 1
#include <osg/Field>
#include <osg/FieldReader>
namespace osg {
class SG_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 // __OSG_FIELD_READER_QUEUE_H

18
include/osg/FileNameUtils Normal file
View File

@@ -0,0 +1,18 @@
#ifndef OSG_FILENAMEUTILS
#define OSG_FILENAMEUTILS 1
#include <osg/Export>
#include <string>
namespace osg {
SG_EXPORT extern std::string getFilePath(const std::string& filename);
SG_EXPORT extern std::string getFileExtension(const std::string& filename);
SG_EXPORT extern std::string getLowerCaseFileExtension(const std::string& filename);
SG_EXPORT extern std::string getSimpleFileName(const std::string& fileName);
SG_EXPORT extern std::string getStrippedName(const std::string& fileName);
};
#endif

66
include/osg/Fog Normal file
View File

@@ -0,0 +1,66 @@
#ifndef OSG_FOG
#define OSG_FOG 1
#include <osg/GL>
#include <osg/Vec4>
#include <osg/Types>
#include <osg/Object>
namespace osg {
/** Fog - encapsulates OpenGL fog state. */
class SG_EXPORT Fog : public Object
{
public :
enum FogMode {
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"; }
static void enable( void );
static void disable( void );
void apply( void );
void setMode( uint mode ) { _mode = mode; }
uint getMode( void ) { return _mode; }
void setDensity( float density ) { _density = density; }
float getDensity( void ) { return _density; }
void setStart( float start ) { _start = start; }
float getStart( void ) { return _start; }
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];
}
protected :
virtual ~Fog( void );
uint _mode;
float _density;
float _start;
float _end;
Vec4 _color;
};
};
#endif

71
include/osg/GL Normal file
View File

@@ -0,0 +1,71 @@
#ifndef OSG_GL
#define OSG_GL 1
#ifdef WIN32
// this works with no problems
// #ifndef _WINDOWS_
// #define WIN32_LEAN_AND_MEAN
// #include <windows.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
#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

468
include/osg/GeoSet Normal file
View File

@@ -0,0 +1,468 @@
#ifndef OSG_GEOSET
#define OSG_GEOSET 1
#include <osg/OSG>
#include <osg/Vec2>
#include <osg/BoundingBox>
#include <osg/Object>
#include <osg/GeoState>
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
be shared for optimal memory usage and graphics performance.
*/
class SG_EXPORT GeoSet : public Object
{
public:
enum PrimitiveType {
NO_TYPE,
POINTS,
LINES,
LINE_STRIP,
FLAT_LINE_STRIP,
LINE_LOOP,
TRIANGLES,
TRIANGLE_STRIP,
FLAT_TRIANGLE_STRIP,
TRIANGLE_FAN,
FLAT_TRIANGLE_FAN,
QUADS,
QUAD_STRIP,
POLYGON
};
enum BindingType {
BIND_OFF,
BIND_OVERALL,
BIND_PERPRIM,
BIND_PERVERTEX,
BIND_DEFAULT
};
enum InterleaveArrayType {
IA_OFF,
IA_V2F,
IA_V3F,
IA_C4UB_V2F,
IA_C4UB_V3F,
IA_C3F_V3F,
IA_N3F_V3F,
IA_C4F_N3F_V3F,
IA_T2F_V3F,
IA_T4F_V4F,
IA_T2F_C4UB_V3F,
IA_T2F_C3F_V3F,
IA_T2F_N3F_V3F,
IA_T2F_C4F_N3F_V3F,
IA_T4F_C4F_N3F_V4F
};
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"; }
// data access methods.
void setNumPrims( int n ) { _numprims = n; }
int getNumPrims( void ) { return _numprims; }
void setPrimType( PrimitiveType type );
PrimitiveType getPrimType( void ) { return _primtype; }
void setPrimLengths( int *lens ) { _primLengths = lens; }
int *getPrimLengths( void ) { return _primLengths; }
void computeNumVerts();
/** get the number of coords required by the defined primitives. */
int getNumCoords() { return _numcoords; }
/** get a pointer to Vec3 coord array. */
Vec3* getCoords() { return _coords; }
/** get the number of indices required by the defined primitives. */
int getNumIndices() { return _numindices; }
/** get the coord index array. */
ushort* getCIndex() { 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.*/
void setCoords( Vec3 *cp, ushort *ci );
/** get the number of normals required by the defined primitives and normals binding.*/
int getNumNormals() { return _numnormals; }
/** get a pointer to Vec3 normal array. */
Vec3* getNormals() { return _normals; }
/** get the number of normal indices required by the defined primitives and normals binding.*/
int getNumNIndices() { return _numnindices; }
/** get the normal index array. */
ushort* getNIndex() { 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 binding to the vertices/primitives/overall.*/
void setNormalBinding( BindingType binding );
BindingType getNormalBinding() { return _normal_binding; }
/** get the number of colors required by the defined primitives and color binding.*/
int getNumColors() { return _numcolors; }
/** get a pointer to Vec4 color array. */
Vec4* getColors() { return _colors; }
/** get the number of colors indices required by the defined primitives and color binding.*/
int getNumCIndices() { return _numcindices; }
/** get the color index array. */
ushort* getColIndex() { return _colindex; }
/** set the colors of the geoset.*/
void setColors( Vec4 *lp );
/** set the colors and color indices of the geoset.*/
void setColors( Vec4 *lp, ushort *li );
/** set the color binding to the vertices/primitives/overall.*/
void setColorBinding( BindingType binding );
BindingType getColorBinding() { return _color_binding; }
/** get the number of texture coords required by the defined primitives and textures binding.*/
int getNumTCoords() { return _numtcoords; }
/** get a pointer to Vec4 color array. */
Vec2* getTCoords() { return _tcoords; }
/** get the number of texture coord indices required by the defined primitives and texture binding.*/
int getNumTIndices() { return _numtindices; }
/** get the texture index array. */
ushort* getTIndex() { 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 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 );
/** 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();
/** Immediately compile this geoset into an OpenGL Display List, set _useDisplayList to true.*/
void compile( void );
bool check();
protected:
GeoSet(const GeoSet&):Object() {}
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 :
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 _numnormals;
int _numnindices;
Vec3 *_normals;
ushort *_nindex;
BindingType _normal_binding;
int _numcolors;
int _numcindices;
Vec4 *_colors;
ushort *_colindex;
BindingType _color_binding;
int _numtcoords;
int _numtindices;
Vec2 *_tcoords;
ushort *_tindex;
BindingType _texture_binding;
void *_iarray;
ushort *_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 );
};
/** Template function for iterating through a GeoSet operating on triangles
with templated functor. Function automatically decomposes quads and polygons
into sub triangles which are passed onto functor.*/
template<class T>
void for_each_triangle(GeoSet& gset,T& op)
{
switch(gset.getPrimType())
{
case(GeoSet::TRIANGLE_STRIP):
case(GeoSet::FLAT_TRIANGLE_STRIP):
{
if (gset.getCIndex())
{
ushort* iptr = gset.getCIndex();
Vec3* vptr = gset.getCoords();
const int numPrim = gset.getNumPrims();
for(int i=0; i<numPrim; ++i )
{
const int primLength = gset.getPrimLengths()[i];
ushort* iend = iptr+primLength;
for(int j = 2; j < primLength; j++ )
{
op(vptr[*(iptr)],vptr[*(iptr+1)],vptr[*(iptr+2)]);
++iptr;
}
iptr=iend;
}
}
else
{
Vec3* vptr = gset.getCoords();
const int numPrim = gset.getNumPrims();
for(int i=0; i<numPrim; ++i )
{
const int primLength = gset.getPrimLengths()[i];
Vec3* vend = vptr+primLength;
for(int j = 2; j < primLength; j++ )
{
op(*(vptr),*(vptr+1),*(vptr+2));
++vptr;
}
vptr=vend;
}
}
}
break;
case(GeoSet::TRIANGLES):
{
if (gset.getCIndex())
{
ushort* iptr = gset.getCIndex();
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
{
Vec3* vptr = gset.getCoords();
const int numPrim = gset.getNumPrims();
for(int i=0; i<numPrim; ++i )
{
op(*(vptr),*(vptr+1),*(vptr+2));
vptr+=3;
}
}
}
break;
case(GeoSet::QUAD_STRIP):
{
if (gset.getCIndex())
{
ushort* iptr = gset.getCIndex();
Vec3* vptr = gset.getCoords();
const int numPrim = gset.getNumPrims();
for(int i=0; i<numPrim; ++i )
{
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
{
Vec3* vptr = gset.getCoords();
const int numPrim = gset.getNumPrims();
for(int i=0; i<numPrim; ++i )
{
const int primLength = gset.getPrimLengths()[i];
Vec3* vend = vptr+primLength;
for(int j = 3; j < primLength; j+=2 )
{
op(*(vptr),*(vptr+1),*(vptr+2));
op(*(vptr),*(vptr+3),*(vptr+2));
vptr+=2;
}
vptr=vend;
}
}
}
break;
case(GeoSet::QUADS):
{
if (gset.getCIndex())
{
ushort* iptr = gset.getCIndex();
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
{
Vec3* vptr = gset.getCoords();
const int numPrim = gset.getNumPrims();
for(int i=0; i<numPrim; ++i )
{
op(*(vptr),*(vptr+1),*(vptr+2));
op(*(vptr),*(vptr+3),*(vptr+2));
vptr+=4;
}
}
}
break;
case(GeoSet::TRIANGLE_FAN):
case(GeoSet::POLYGON):
{
if (gset.getCIndex())
{
ushort* iptr = gset.getCIndex();
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)];
ushort* iend = iptr+primLength;
++iptr;
for(int j = 2; j < primLength; ++j )
{
op(start,vptr[*(iptr)],vptr[*(iptr+1)]);
++iptr;
}
iptr=iend;
}
}
}
else
{
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;
Vec3* vend = vptr+primLength;
++vptr;
for(int j = 2; j < primLength; ++j)
{
op(start,*(vptr),*(vptr+1));
++vptr;
}
vptr = vend;
}
}
}
}
break;
default:
break;
}
};
};
#endif

150
include/osg/GeoState Normal file
View File

@@ -0,0 +1,150 @@
#ifndef OSG_GEOSTATE
#define OSG_GEOSTATE 1
#include <osg/OSG>
#include <osg/Texture>
#include <osg/TexGen>
#include <osg/Light>
#include <osg/Material>
#include <osg/TexEnv>
#include <osg/Transparency>
#include <osg/Lighting>
#include <osg/Fog>
#include <osg/TexMat>
#include <osg/CullFace>
#include <osg/Point>
#include <osg/PolygonOffset>
#include <osg/AlphaFunc>
namespace osg {
class Input;
class Output;
/**
Encapsulates OpenGL state modes and attributes.
Used to specificy textures etc of osg::GeoSet's which hold references
to a single osg::GeoState. GeoState can be shared between GeoSet's
and is recommend if possible as it minimize expensive state changes
in the graphics pipeline.
*/
class SG_EXPORT GeoState : public Object
{
public :
enum AttributeType
{
ANTIALIAS,
FACE_CULL,
FOG,
LIGHTING,
MATERIAL,
POINT,
POLYGON_OFFSET,
TEXENV,
TEXGEN,
TEXMAT,
TEXTURE,
TRANSPARENCY,
WIREFRAME,
ALPHAFUNC
};
enum AttributeMode
{
INHERIT,
OFF,
ON,
OVERRIDE_OFF,
OVERRIDE_ON,
};
GeoState();
static GeoState* instance();
virtual Object* clone() const { return new GeoState(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<GeoState*>(obj)!=NULL; }
const char* className() const { return "GeoState"; }
/** set all the modes to on or off so that it defines a
complete state, typically used for a default global state.*/
void setGlobalDefaults();
/** set all the modes to inherit, typically used to signifiy
nodes which inherit all of their modes for the global state.*/
void setAllToInherit();
void setMode(AttributeType type, AttributeMode mode);
AttributeMode getMode(AttributeType type) const;
void setAttribute(AttributeType type, Object *attribute);
Object* getAttribute(AttributeType type) const;
bool isTransparent() { return _transparencing==ON; }
void apply();
void apply(GeoState* global,GeoState* prev);
bool check();
static AttributeMode combineMode(const AttributeMode g,const AttributeMode p,const AttributeMode c)
{
AttributeMode gp = mergeMode(g,p);
AttributeMode gc = mergeMode(g,c);
if (gc==gp) return INHERIT;
else return gc;
}
static AttributeMode mergeMode(const AttributeMode lhs,const AttributeMode rhs)
{
AttributeMode mode;
if (rhs==INHERIT || lhs==OVERRIDE_OFF || lhs==OVERRIDE_ON) mode = lhs;
else mode = rhs;
if (mode==OVERRIDE_OFF) return OFF;
else if (mode==OVERRIDE_OFF) return ON;
return mode;
}
protected :
virtual ~GeoState();
GeoState(const GeoState&):Object() {}
GeoState& operator = (const GeoState&) { return *this; }
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
bool matchModeStr(const char* str, AttributeMode& mode);
const char* getModeStr(AttributeMode flag);
// Modes
AttributeMode _transparencing;
AttributeMode _face_culling;
AttributeMode _lighting;
AttributeMode _texturing;
AttributeMode _fogging;
AttributeMode _texgening;
AttributeMode _antialiasing;
AttributeMode _colortable;
AttributeMode _pointSmoothing;
AttributeMode _polygonOffsetting;
AttributeMode _alphaTesting;
// Attributes
ref_ptr<Texture> _texture;
ref_ptr<TexGen> _texgen;
ref_ptr<Material> _material;
ref_ptr<TexEnv> _texenv;
ref_ptr<Transparency> _transparency;
ref_ptr<TexMat> _texmat;
ref_ptr<Fog> _fog;
ref_ptr<Point> _point;
ref_ptr<PolygonOffset> _polygonOffset;
ref_ptr<CullFace> _cullFace;
ref_ptr<AlphaFunc> _alphaFunc;
};
};
#endif

108
include/osg/Geode Normal file
View File

@@ -0,0 +1,108 @@
#ifndef OSG_GEODE
#define OSG_GEODE 1
#include <osg/OSG>
#include <osg/Node>
#include <osg/GeoSet>
#include <osg/NodeVisitor>
#include <vector>
namespace osg {
/** Leaf Node for grouping GeoSets.*/
class SG_EXPORT Geode : public Node
{
public:
typedef std::vector< ref_ptr<GeoSet> > GeoSetList;
Geode();
virtual Object* clone() const { return new Geode(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<Geode*>(obj)!=NULL; }
virtual const char* className() const { return "Geode"; }
virtual void accept(NodeVisitor& nv) { nv.apply(*this); }
/** Add GeoSet 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
* sphere to force it to recompute on next getBound() and return true for success.
* Otherwise return false.
*/
virtual bool addGeoSet( GeoSet *gset );
/** Remove GeoSet 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 );
/** Replace specified GeoSet with another GeoSet.
* 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
* add newGset. If newGset is NULL then return false and do
* not remove origGset.
*/
virtual bool replaceGeoSet( GeoSet *origGset, GeoSet *newGset );
/** return the number of geoset's.*/
int getNumGeosets( void ) const { return _geosets.size(); }
/** return geoset at position i.*/
GeoSet* getGeoSet( int i ) { return _geosets[i].get(); }
/** return true is geoset is contained within Geode.*/
bool containsGeoSet( GeoSet* gset)
{
for (GeoSetList::iterator itr=_geosets.begin();
itr!=_geosets.end();
++itr)
{
if (itr->get()==gset) return true;
}
return false;
}
/** return the iterator postion for specified GeoSet.
* return _geoset.end() if gset not is contained in Geode.
*/
GeoSetList::iterator findGeoSet( GeoSet* gset)
{
for (GeoSetList::iterator itr=_geosets.begin();
itr!=_geosets.end();
++itr)
{
if (itr->get()==gset) return itr;
}
return _geosets.end();
}
/** complile OpenGL Display List for each geoset.*/
void compileGeoSets( void );
protected:
virtual ~Geode();
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
virtual bool computeBound( void );
GeoSetList _geosets;
};
};
#endif

106
include/osg/Group Normal file
View File

@@ -0,0 +1,106 @@
#ifndef OSG_GROUP
#define OSG_GROUP 1
#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
with memory management handled automatically via osg::Referenced.
*/
class SG_EXPORT Group : public Node
{
public :
typedef std::vector<ref_ptr<Node> > ChildList;
Group();
virtual Object* clone() const { return new Group(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<Group*>(obj)!=NULL; }
virtual const char* className() const { return "Group"; }
virtual void accept(NodeVisitor& nv) { nv.apply(*this); }
virtual void traverse(NodeVisitor& nv);
/** Add Node to Group.
* 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.
*/
virtual bool addChild( Node *child );
/** Remove Node from Group.
* If Node is contained in Group then remove it from the child
* list, decrement its reference count, and dirty the
* bounding sphere to force it to recompute on next getBound() and
* return true for success. If Node is not found then return false
* and do not change the reference count of the Node.
*/
virtual bool removeChild( Node *child );
/** Replace specified Node with another Node.
* Decrement the reference count origNode and increments the
* reference count of newNode, and dirty the bounding sphere
* 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.
*/
virtual bool replaceChild( Node *origChild, Node* newChild );
/** return the number of chilren nodes.*/
int getNumChildren( void ) { return _children.size(); }
/** return child node at position i.*/
Node *getChild( int i ) { return _children[i].get(); }
/** return true is node is contained within Group.*/
bool containsNode( Node* node )
{
for (ChildList::iterator itr=_children.begin();
itr!=_children.end();
++itr)
{
if (itr->get()==node) return true;
}
return false;
}
/** return the iterator postion for specified Node.
* return _chilren.end() if node is not contained in Group.
*/
ChildList::iterator findNode( Node* node )
{
for (ChildList::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);
ChildList _children;
bool computeBound( void );
};
};
#endif

98
include/osg/Image Normal file
View File

@@ -0,0 +1,98 @@
#ifndef OSG_IMAGE
#define OSG_IMAGE 1
#include <osg/Object>
#include <osg/OSG>
namespace osg {
class Output;
class Input;
/** Image class for encapsulating the storage texture image data.*/
class SG_EXPORT Image : public Object
{
public :
Image();
virtual Object* clone() const { return new Image(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<Image*>(obj)!=NULL; }
virtual const char* className() const { return "Image"; }
const char* getFileName() { return _fileName; }
void setFileName(const char* fileName);
/** set the image data and format.
* note, when no 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,
unsigned char *data,
int packing=-1);
/** Width of image.*/
int s() { return _s; }
/** Height of image.*/
int t() { return _t; }
/** Depth of image.*/
int r() { return _r; }
int internalFormat() { return _internalFormat; }
unsigned int pixelFormat() { return _pixelFormat; }
unsigned int dataType() { return _dataType; }
unsigned int packing() { return _packing; }
/** raw image data.*/
unsigned char *data() { return _data; }
/** Scale image to specified size. */
void scaleImage(int s,int t,int r);
/** Ensure image dimensions are a power of two.
* Mip Mapped texture require the image dimensions to be
* power of two.
*/
void ensureDimensionsArePowerOfTwo();
protected :
virtual ~Image();
// Image(const Image&) {}
// Image& operator = (const Image& image) {}
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
char* _fileName;
int _s, _t, _r;
int _internalFormat;
unsigned int _pixelFormat;
unsigned int _dataType;
unsigned int _packing;
unsigned char *_data;
};
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.
*/
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);
};
#endif // __SG_IMAGE_H

49
include/osg/Input Normal file
View File

@@ -0,0 +1,49 @@
#ifndef OSG_INPUT
#define OSG_INPUT 1
#include <osg/FieldReaderIterator>
#include <map>
#include <string>
namespace osg {
class Object;
class Image;
class Node;
/** Class for managing the reading of ASCII .osg files.*/
class SG_EXPORT Input : public FieldReaderIterator
{
public:
// Will extend to handle #DEF and use
// functionality similar to Inventor,
// and add the ability to handle #include
// from within the OSG file format.
Input();
virtual ~Input();
virtual Object* readObject();
virtual Object* readObject(const std::string& fileName);
virtual Image* readImage();
virtual Image* readImage(const std::string& fileName);
virtual Node* readNode();
virtual Node* readNode(const std::string& fileName);
virtual Object* getObjectForUniqueID(const std::string& uniqueID);
virtual void regisiterUniqueIDForObject(const std::string& uniqueID,Object* obj);
private:
typedef std::map<std::string,Object*> UniqueIDToObjectMapping;
UniqueIDToObjectMapping _uniqueIDToObjectMap;
};
};
#endif // __SG_INPUT_H

67
include/osg/LOD Normal file
View File

@@ -0,0 +1,67 @@
#ifndef OSG_LOD
#define OSG_LOD 1
#include <osg/Switch>
#include <vector>
namespace osg {
/** LOD - Level Of Detail group node which allows switching between children
depending on distance from eye point.
Typical uses are for load balancing - objects further away from
the eye point are rendered at a lower level of detail, and at times
of high stress on the graphics pipeline lower levels of detail can
also be chosen.
*/
class SG_EXPORT LOD : public Group
{
public :
LOD() {}
virtual Object* clone() const { return new LOD(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<LOD*>(obj)!=NULL; }
virtual const char* className() const { return "LOD"; }
virtual void accept(NodeVisitor& nv) { nv.apply(*this); }
virtual void traverse(NodeVisitor& nv);
/** Sets the value of range list element index to range which
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]; }
/** returns the number of ranges currently set.*/
int getNumRanges() { 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; }
/** return the LOD center point. */
const Vec3& getCenter() { 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);
protected :
virtual ~LOD() {}
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
typedef std::vector<float> RangeList;
RangeList _rangeList;
RangeList _rangeList2;
Vec3 _center;
};
};
#endif

143
include/osg/Light Normal file
View File

@@ -0,0 +1,143 @@
#ifndef OSG_LIGHT
#define OSG_LIGHT 1
#include <osg/GL>
#include <osg/OSG>
#include <osg/Vec4>
namespace osg {
/** Light state class which encapsulates OpenGL glLight() functionality.*/
class SG_EXPORT Light : public Object
{
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 the name of the node's class type.*/
virtual const char* className() const { return "Light"; }
/**
* Turn the light on.
* Calling this method doesn't directly affect OpenGL's lighting mode.
*/
void on( void ) { _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 );
/** Apply the light's state to the OpenGL state machine. */
void apply( void );
/** Set the ambient component of the light. */
void setAmbient( const Vec4& ambient ) { _ambient = ambient; }
/** Get the ambient component of the light. */
const Vec4& getAmbient() const { return _ambient; }
/** Set the diffuse component of the light. */
void setDiffuse( const Vec4& diffuse ) { _diffuse = diffuse; }
/** Get the diffuse component of the light. */
const Vec4& getDiffuse() const { return _diffuse; }
/** Set the specular component of the light. */
void setSpecular( const Vec4& specular ) { _specular = specular; }
/** Get the specular component of the light. */
const Vec4& getSpecular() const { return _specular; }
/** Set the position of the light. */
void setPosition( const Vec4& position ) { _position = position; }
/** Get the position of the light. */
const Vec4& getPosition() const { return _position; }
/** Set the direction of the light. */
void setDirection( const Vec3& direction ) { _direction = direction; }
/** Get the direction of the light. */
const Vec3& getDirection() const { return _direction; }
/** Set the constant attenuation of the light. */
void setConstantAttenuation( float constant_attenuation ) { _constant_attenuation = constant_attenuation; }
/** Get the constant attenuation of the light. */
float setConstantAttenuation() const { return _constant_attenuation; }
/** Set the linear attenuation of the light. */
void setLinearAttenuation ( float linear_attenuation ) { _linear_attenuation = linear_attenuation; }
/** Get the linear attenuation of the light. */
float getLinearAttenuation () const { return _linear_attenuation; }
/** Set the quadratic attenuation of the light. */
void setQuadraticAttenuation ( float quadratic_attenuation ) { _quadratic_attenuation = quadratic_attenuation; }
/** Get the quadratic attenuation of the light. */
float getQuadraticAttenuation() const { return _quadratic_attenuation; }
/** Set the spot exponent of the light. */
void setSpotExponent( float spot_exponent ) { _spot_exponent = spot_exponent; }
/** Get the spot exponent of the light. */
float getSpotExponent() const { return _spot_exponent; }
/** Set the spot cutoff of the light. */
void setSpotCutoff( float spot_cutoff ) { _spot_cutoff = spot_cutoff; }
/** Get the spot cutoff of the light. */
float getSpotCutoff() { return _spot_cutoff; }
/**
* Capture the lighting settings of the current OpenGL state
* and store them in this object.
*/
void captureLightState();
protected :
virtual ~Light( void );
/** Initialize the light's settings with some decent defaults. */
void init( void );
int _lightnum; // OpenGL light number
bool _on; // on/off state
Vec4 _ambient; // r, g, b, w
Vec4 _diffuse; // r, g, b, w
Vec4 _specular; // r, g, b, w
Vec4 _position; // x, y, z, w
Vec3 _direction; // x, y, z
float _constant_attenuation; // constant
float _linear_attenuation; // linear
float _quadratic_attenuation; // quadratic
float _spot_exponent; // exponent
float _spot_cutoff; // spread
static int _currentLightNum; // current max. OpenGL light number
};
};
#endif

42
include/osg/LightSource Normal file
View File

@@ -0,0 +1,42 @@
#ifndef OSG_LIGHTSOURCE
#define OSG_LIGHTSOURCE 1
#include <osg/Node>
#include <osg/NodeVisitor>
#include <osg/Light>
namespace osg {
/** Leaf Node for defining a light in the scene.*/
class SG_EXPORT LightSource : public Node
{
public:
LightSource();
virtual Object* clone() const { return new LightSource(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<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; }
/** Get the attached light.*/
Light* getLight() { return _light.get(); }
protected:
virtual ~LightSource();
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
virtual bool computeBound( void );
ref_ptr<Light> _light;
};
};
#endif

21
include/osg/Lighting Normal file
View File

@@ -0,0 +1,21 @@
#ifndef OSG_LIGHTING
#define OSG_LIGHTING 1
#include <osg/Export>
namespace osg {
/** Class to globally control OpenGL's lighting.*/
class SG_EXPORT Lighting
{
public :
/** Enable lighting.*/
static void enable();
/** Disable lighting.*/
static void disable();
};
};
#endif

100
include/osg/Material Normal file
View File

@@ -0,0 +1,100 @@
#ifndef OSG_MATERIAL
#define OSG_MATERIAL 1
#include <osg/GL>
#include <osg/OSG>
#include <osg/Vec4>
#include <osg/Object>
namespace osg {
class Input;
class Output;
class SG_EXPORT Material : public Object
{
public :
enum MaterialFace {
FACE_FRONT = GL_FRONT,
FACE_BACK = GL_BACK,
FACE_FRONT_AND_BACK = GL_FRONT_AND_BACK
};
enum ColorMode {
AMBIENT = GL_AMBIENT,
DIFFUSE = GL_DIFFUSE,
SPECULAR = GL_SPECULAR,
EMISSION = GL_EMISSION,
AMBIENT_AND_DIFFUSE = GL_AMBIENT_AND_DIFFUSE,
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"; }
void apply( void );
void setColorMode(ColorMode mode) { _colorMode = mode; }
void setAmbient( MaterialFace face, const Vec4& ambient );
const Vec4& getAmbient(MaterialFace face) const;
bool getAmbientFrontAndBack() { return _ambientFrontAndBack; }
void setDiffuse( MaterialFace face, const Vec4& diffuse );
const Vec4& getDiffuse(MaterialFace face) const;
bool getDiffuseFrontAndBack() { return _diffuseFrontAndBack; }
void setSpecular( MaterialFace face, const Vec4& specular );
const Vec4& getSpecular(MaterialFace face) const;
bool getSpecularFrontAndBack() { return _specularFrontAndBack; }
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; }
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);
ColorMode _colorMode;
bool _ambientFrontAndBack;
Vec4 _ambientFront; // r, g, b, w
Vec4 _ambientBack; // r, g, b, w
bool _diffuseFrontAndBack;
Vec4 _diffuseFront; // r, g, b, w
Vec4 _diffuseBack; // r, g, b, w
bool _specularFrontAndBack;
Vec4 _specularFront; // r, g, b, w
Vec4 _specularBack; // r, g, b, w
bool _emissionFrontAndBack;
Vec4 _emissionFront; // r, g, b, w
Vec4 _emissionBack; // r, g, b, w
bool _shininessFrontAndBack;
float _shininessFront; // values 0 - 1.0
float _shininessBack; // values 0 - 1.0
};
};
#endif

107
include/osg/Matrix Normal file
View File

@@ -0,0 +1,107 @@
#ifndef OSG_MATRIX
#define OSG_MATRIX 1
#include <osg/Object>
#include <osg/Types>
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.
*/
class SG_EXPORT Matrix : public Object
{
public:
Matrix();
Matrix(const Matrix& matrix);
Matrix( 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);
Matrix& operator = (const Matrix& matrix);
virtual ~Matrix();
static Matrix* instance();
virtual Object* clone() const { return new Matrix(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<Matrix*>(obj)!=NULL; }
virtual const char* className() const { return "Matrix"; }
void makeIdent();
void set(const float* m);
void copy(const Matrix& matrix);
void makeScale(float sx, float sy, float sz);
void preScale( float sx, float sy, float sz, const Matrix& m );
void postScale( const Matrix& m, float sx, float sy, float sz );
void preScale( float sx, float sy, float sz );
void postScale( float sx, float sy, float sz );
void makeTrans( float tx, float ty, float tz );
void preTrans( float tx, float ty, float tz, const Matrix& m );
void postTrans( const Matrix& m, float tx, float ty, float tz );
void preTrans( float tx, float ty, float tz );
void postTrans( float tx, float ty, float tz );
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 );
void preRot( float deg, float x, float y, float z );
void postRot( float deg, float x, float y, float z );
void setTrans( float tx, float ty, float tz );
void setTrans( const Vec3& v );
Vec3 getTrans() const { return Vec3(_mat[3][0],_mat[3][1],_mat[3][2]); }
void preMult(const Matrix& m);
void postMult(const Matrix& m);
void mult(const Matrix& lhs,const Matrix& rhs);
Matrix operator * (const Matrix& m) const;
inline Vec3 operator * (const Vec3& v) const;
inline friend Vec3 operator * (const Vec3& v,const Matrix& m);
bool invert(const Matrix& m);
public :
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]) ;
return Vec3( (_mat[0][0]*v.x() + _mat[0][1]*v.y() + _mat[0][2]*v.z() + _mat[0][3])*d,
(_mat[1][0]*v.x() + _mat[1][1]*v.y() + _mat[1][2]*v.z() + _mat[1][3])*d,
(_mat[2][0]*v.x() + _mat[2][1]*v.y() + _mat[2][2]*v.z() + _mat[2][3])*d) ;
}
// 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]) ;
return Vec3( (m._mat[0][0]*v.x() + m._mat[1][0]*v.y() + m._mat[2][0]*v.z() + m._mat[3][0])*d,
(m._mat[0][1]*v.x() + m._mat[1][1]*v.y() + m._mat[2][1]*v.z() + m._mat[3][1])*d,
(m._mat[0][2]*v.x() + m._mat[1][2]*v.y() + m._mat[2][2]*v.z() + m._mat[3][2])*d);
}
};
#endif

211
include/osg/Node Normal file
View File

@@ -0,0 +1,211 @@
#ifndef OSG_NODE
#define OSG_NODE 1
#include <osg/Types>
#include <osg/Object>
#include <osg/BoundingSphere>
#include <string>
#include <vector>
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).
*/
class SG_EXPORT Node : public Object
{
public:
/** Construct a node.
Initialize the parent list to empty, node name to "" and
bounding sphere dirty flag to true.*/
Node();
/** 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; }
/** return the name of the node's class type.*/
virtual const char* className() const { return "Node"; }
/** Visitor Pattern : calls the apply method of a NodeVisitor with this node's type.*/
virtual void accept(NodeVisitor& nv);
/** Traverse upwards : calls parents' accept method with NodeVisitor.*/
virtual void ascend(NodeVisitor& nv);
/** Traverse downwards : calls children's accept method with NodeVisitor.*/
virtual void traverse(NodeVisitor& /*nv*/) {}
/** Set the name of node using C++ style string.*/
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; }
/** Get the name of node.*/
const std::string& getName( void ) { 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; }
/**
* Get a single parent of node.
* @param i index of the parent to get.
* @return the parent i.
*/
Group* getParent(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(); }
/**
* Set user data. See MemoryAdapter documention for details
* of how to specify memory managament of _userData.
*/
void setUserData(void* data,MemoryAdapter* ma=0L)
{
if (_userData && _memoryAdapter.valid()) _memoryAdapter->decrementReference(_userData);
_userData = data;
_memoryAdapter = ma;
if (_userData && _memoryAdapter.valid()) _memoryAdapter->incrementReference(_userData);
}
/** Get user data.*/
void* getUserData() const { return _userData; }
/** Get the memory adapter associated with _userData.*/
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; }
/** Get the node Mask. Note, node mask is will be replaced by TraversalMask.*/
NodeMask getNodeMask() { return _nodeMask; }
/** A vector of std::string's which are used to describe the object.*/
typedef std::vector<std::string> DescriptionList;
/** Get the description list of the const node.*/
const DescriptionList& getDescriptions() const { return _descriptions; }
/** Get the description list of the const node.*/
DescriptionList& getDescriptions() { return _descriptions; }
/** Get a single const description of the const node.*/
const std::string& getDescription(int i) const { return _descriptions[i]; }
/** Get a single description of the node.*/
std::string& getDescription(int i) { return _descriptions[i]; }
/** Get the number of descriptions of the node.*/
int getNumDescriptions() const { return _descriptions.size(); }
/** Add a description string to the node.*/
void addDescription(const std::string& desc) { _descriptions.push_back(desc); }
/** get the bounding sphere of node.
Using lazy evaluation computes the bounding sphere if it is 'dirty'.*/
const BoundingSphere& getBound();
/** Mark this node's bounding sphere dirty.
Forcing it to be computed on the next call to getBound().*/
void dirtyBound();
protected:
/** Node destructor. Note, is protected so that Nodes cannot
be deleted other than by being dereferenced and the reference
count being zero (see osg::Referenced), preventing the deletion
of nodes which are still in use. This also means that
Node's cannot be created on stack i.e Node node will not compile,
forcing all nodes to be created on the heap i.e Node* node
= new Node().*/
virtual ~Node();
/**
* 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 ) ;
BoundingSphere _bsphere;
bool _bsphere_computed;
std::string _name;
ParentList _parents;
friend Group;
void* _userData;
ref_ptr<MemoryAdapter> _memoryAdapter;
NodeMask _nodeMask;
DescriptionList _descriptions;
};
/** A vector of Nodes pointers which is used to describe the path from a root node to a descendant.*/
typedef std::vector<Node*> NodePath;
};
#endif

94
include/osg/NodeVisitor Normal file
View File

@@ -0,0 +1,94 @@
#ifndef OSG_NODEVISITOR
#define OSG_NODEVISITOR 1
#include <osg/Node>
namespace osg {
class Geode;
class Billboard;
class LightSource;
class Group;
class DCS;
class LOD;
class Sequence;
class Scene;
class Switch;
/** Visitor for type safe operations on osg::Node's.
Based on GOF's Visitor pattern.*/
class SG_EXPORT NodeVisitor : public Referenced
{
public:
enum TraversalMode {
TRAVERSE_NONE,
TRAVERSE_PARENTS,
TRAVERSE_ALL_CHILDREN,
TRAVERSE_ACTIVE_CHILDREN,
TRAVERSE_VISITOR
};
NodeVisitor(TraversalMode tm=TRAVERSE_NONE);
virtual ~NodeVisitor();
/** 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);
/** Get the traversal mode.*/
TraversalMode getTraverseMode() { return _traverseMode; }
/** Set a visitor to handle traversal.
Overides the traverse mode setting it to TRAVERSE_VISITOR.*/
void setTraverseVisitor(NodeVisitor* nv);
/** Get the traverse visitor, returns NULL if none is attached.*/
NodeVisitor* getTraverseVisitor() { return _traverseVisitor; }
/** Inline method for passing handling traversal of a nodes.
If you intend to use the visitor for actively traversing
the scene graph then make sure the accept() methods call
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);
}
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(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); }
protected:
NodeVisitor* _traverseVisitor;
TraversalMode _traverseMode;
};
/** Convinience functor for assisting visiting of arrays of osg::Node's.*/
struct NodeAcceptOp
{
NodeVisitor& _nv;
NodeAcceptOp(NodeVisitor& nv):_nv(nv) {}
void operator () (Node* node) { node->accept(_nv); }
void operator () (ref_ptr<Node> node) { node->accept(_nv); }
};
};
#endif

64
include/osg/Notify Normal file
View File

@@ -0,0 +1,64 @@
#ifndef OSG_NOTIFY
#define OSG_NOTIFY 1
#include <osg/Export>
#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 {
enum NotifySeverity {
ALWAYS=0,
FATAL=1,
WARN=2,
NOTICE=3,
INFO=4,
DEBUG=5,
FP_DEBUG=6
};
extern NotifySeverity g_NotifyLevel;
extern ofstream *g_absorbStreamPtr;
SG_EXPORT extern void setNotifyLevel(NotifySeverity severity);
SG_EXPORT extern int getNotifyLevel();
#ifdef WIN32
inline ostream& notify(NotifySeverity severity=INFO)
{
if (severity<=osg::WARN) return cerr;
else return cout;
}
#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

15
include/osg/OSG Normal file
View File

@@ -0,0 +1,15 @@
#ifndef OSG_OSG
#define OSG_OSG 1
#include <osg/Node>
namespace osg {
SG_EXPORT extern void Init( void );
SG_EXPORT extern void SetFilePath( const char *_path );
SG_EXPORT extern char *FindFile( const char *file );
SG_EXPORT extern char *findDSO( const char *name );
};
#endif

76
include/osg/Object Normal file
View File

@@ -0,0 +1,76 @@
#ifndef OSG_OBJECT
#define OSG_OBJECT 1
#include <osg/Referenced>
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.
*/
class SG_EXPORT Object : public Referenced
{
public:
/** Construct an object. Note Object is a pure virtual base class
and therefore cannot be constructed on its own, only derived
classes which overide the clone and className methods are
concrete classes and can be constructed.*/
Object() {}
/** return a shallow copy of a node, with Object* return type.
Must be defined by derived classes.*/
virtual Object* clone() const = 0;
virtual bool isSameKindAs(Object*) { 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
be deleted other than by being derefernced and the reference
count being zero (see osg::Referenced), preventing the deletion
of nodes which are still in use. This also means that
Node's cannot be created on stack i.e Node node will not compile,
forcing all nodes to be created on the heap i.e Node* node
= new Node().*/
virtual ~Object() {}
/** 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.*/
Object(Object&): Referenced() {}
Object& operator = (const Object&) { return *this; }
};
};
#endif

98
include/osg/Output Normal file
View File

@@ -0,0 +1,98 @@
#ifndef OSG_OUTPUT
#define OSG_OUTPUT 1
#include <osg/Export>
#include <string>
#include <map>
#ifdef OSG_USE_IO_DOT_H
#include <fstream.h>
#else
#include <fstream>
using namespace std;
#endif
namespace osg {
class Object;
/** ofstream wrapper class for adding support for indenting.
Used in output of .osg ASCII files to improve their readability.*/
class SG_EXPORT Output : public ofstream
{
public:
Output();
virtual ~Output();
Output& indent();
int getIndentStep() const { return _indentStep; }
void setIndentStep(int step) { _indentStep = step; }
int getIndent() const { return _indent; }
void setIndent(int indent) { _indent = indent; }
int getNumIndicesPerLine() const { return _numIndicesPerLine; }
void setNumIndicesPerLine(int num) { _numIndicesPerLine = num; }
void moveIn();
void moveOut();
bool getUniqueIDForObject(Object* obj,std::string& uniqueID);
bool createUniqueIDForObject(Object* obj,std::string& uniqueID);
bool registerUniqueIDForObject(Object* obj,std::string& uniqueID);
protected:
// prevent copy construction and assignment.
Output(const Output&) : ofstream() {}
Output& operator = (const Output&) { return *this; }
virtual void _init();
virtual void _free();
int _indent;
int _indentStep;
int _numIndicesPerLine;
typedef std::map<Object*,std::string> UniqueIDToLabelMapping;
UniqueIDToLabelMapping _objectToUniqueIDMap;
};
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

49
include/osg/Point Normal file
View File

@@ -0,0 +1,49 @@
#ifndef OSG_POINT
#define OSG_POINT 1
#include <osg/Export>
#include <osg/Object>
#include <osg/Vec3>
namespace osg {
class Input;
class Output;
class SG_EXPORT Point : public Object
{
public :
Point();
static Point* instance();
virtual Object* clone() const { return new Point(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<Point*>(obj)!=NULL; }
virtual const char* className() const { return "Point"; }
void setSize(float size);
void setFadeThresholdSize(float fadeThresholdSize);
void setDistanceAttenuation(const Vec3& distanceAttenuation);
static void enableSmooth( void );
static void disableSmooth( void );
void apply( void );
static void init_GL_EXT();
protected :
virtual ~Point();
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
float _size;
float _fadeThresholdSize;
Vec3 _distanceAttenuation;
};
};
#endif

44
include/osg/PolygonOffset Normal file
View File

@@ -0,0 +1,44 @@
#ifndef OSG_POLYGONOFFSET
#define OSG_POLYGONOFFSET 1
#include <osg/Export>
#include <osg/Object>
#include <osg/Vec3>
namespace osg {
class Input;
class Output;
class SG_EXPORT PolygonOffset : public Object
{
public :
PolygonOffset();
static PolygonOffset* instance();
virtual Object* clone() const { return new PolygonOffset(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<PolygonOffset*>(obj)!=NULL; }
virtual const char* className() const { return "PolygonOffset"; }
void setOffset(float factor,float units);
static void enable( void );
static void disable( void );
void apply( void );
protected :
virtual ~PolygonOffset();
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
float _factor;
float _units;
};
};
#endif

231
include/osg/Quat Normal file
View File

@@ -0,0 +1,231 @@
#ifndef OSG_QUAT
#define OSG_QUAT 1
#include <osg/Export>
#include <math.h>
#include <osg/Vec4>
#include <osg/Vec3>
#include <osg/Matrix>
namespace osg {
/** A quaternion class. It can be used to represent an orientation in 3D space.*/
class SG_EXPORT Quat
{
public:
/* ----------------------------------------------------------
DATA MEMBERS
The only data member is a
Vec4 which holds the elements
In other words, osg:Quat is composed of an osg::Vec4
The osg::Quat aggregates an osg::Vec4
These seem to be different jargons for the same thing :-)
---------------------------------------------------------- */
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 );
/* ----------------------------------
Methods to access data members
---------------------------------- */
inline Vec4 asVec4( void ) const
{
return _fv;
}
inline Vec3 asVec3( void ) const
{
return Vec3(_fv[0], _fv[1], _fv[2]);
}
/* -------------------------------------------------------------
BASIC ARITHMETIC METHODS
Implemented in terms of Vec4s. Some Vec4 operators, e.g.
operator* are not appropriate for quaternions (as
mathematical objects) so they are implemented differently.
Also define methods for conjugate and the multiplicative inverse.
------------------------------------------------------------- */
/// Multiply by scalar
inline Quat operator * (const float& rhs) const
{
return Quat(_fv*rhs);
}
/// Unary multiply by scalar
inline Quat& operator *= (const float& rhs)
{
_fv*=rhs;
return *this; // enable nesting
}
/// Binary multiply
inline 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],
_fv[3]*rhs._fv[2] + _fv[0]*rhs._fv[1] - _fv[1]*rhs._fv[0] + _fv[2]*rhs._fv[3],
_fv[3]*rhs._fv[3] - _fv[0]*rhs._fv[0] - _fv[1]*rhs._fv[1] - _fv[2]*rhs._fv[2] );
}
/// Unary multiply
inline Quat& operator*=(const Quat& rhs)
{
float x = _fv[3]*rhs._fv[0] + _fv[0]*rhs._fv[3] + _fv[1]*rhs._fv[2] - _fv[2]*rhs._fv[1];
float y = _fv[3]*rhs._fv[1] - _fv[0]*rhs._fv[2] + _fv[1]*rhs._fv[3] + _fv[2]*rhs._fv[0];
float z = _fv[3]*rhs._fv[2] + _fv[0]*rhs._fv[1] - _fv[1]*rhs._fv[0] + _fv[2]*rhs._fv[3];
_fv[3] = _fv[3]*rhs._fv[3] - _fv[0]*rhs._fv[0] - _fv[1]*rhs._fv[1] - _fv[2]*rhs._fv[2];
_fv[2] = z;
_fv[1] = y;
_fv[0] = x;
return (*this); // enable nesting
}
/// Divide by scalar
inline Quat operator / (const float& rhs) const
{
return Quat(_fv/rhs);
}
/// Unary divide by scalar
inline Quat& operator /= (const float& rhs)
{
_fv/=rhs;
return *this;
}
/// Binary divide
inline Quat operator/(const Quat& denom) const
{
return ( (*this) * denom.inverse() );
}
/// Unary divide
inline Quat& operator/=(const Quat& denom)
{
(*this) = (*this) * denom.inverse();
return (*this); // enable nesting
}
/// Binary addition
inline Quat operator + (const Quat& rhs) const
{
return Quat( _fv + rhs._fv );
}
/// Unary addition
inline Quat& operator += (const Quat& rhs)
{
_fv += rhs._fv;
return *this; // enable nesting
}
/// Binary subtraction
inline Quat operator - (const Quat& rhs) const
{
return Quat( _fv - rhs._fv );
}
/// Unary subtraction
inline Quat& operator -= (const Quat& rhs)
{
_fv-=rhs._fv;
return *this; // enable nesting
}
/** Negation operator - returns the negative of the quaternion.
Basically just calls operator - () on the Vec4 */
inline Quat operator - () const
{
return Quat ( -_fv );
}
/// Length of the quaternion = sqrt( vec . vec )
float length( void ) const
{
return _fv.length();
}
/// Length of the quaternion = vec . vec
float length2( void ) const
{
return _fv.length2();
}
/// Conjugate
inline Quat conj ( void ) const
{
return Quat( -_fv[0], -_fv[1], -_fv[2], _fv[3] );
}
/// Multiplicative inverse method: q^(-1) = q^*/(q.q^*)
inline Quat inverse ( void ) const
{
return conj() / length2();
}
/* --------------------------------------------------------
METHODS RELATED TO ROTATIONS
Set a quaternion which will perform a rotation of an
angle around the axis given by the vector (x,y,z).
Should be written to also accept an angle and a Vec3?
Define Spherical Linear intERPolation method also
Not inlined - see the Quat.cpp file for implementation
-------------------------------------------------------- */
void makeRot ( const float angle,
const float x, const float y, const float z );
void makeRot ( const float angle, const Vec3& vec );
/** Make a rotation Quat which will rotate vec1 to vec2.
Generally take adot product to get the angle between these
and then use a cross product to get the rotation axis
Watch out for the two special cases of when the vectors
are co-incident or opposite in direction.*/
void makeRot( const Vec3& vec1, const Vec3& vec2 );
/** Return the angle and vector components represented by the quaternion.*/
void getRot ( float& angle, float& x, float& y, float& z ) const;
/** Return the angle and vector represented by the quaternion.*/
void getRot ( float& angle, Vec3& vec ) const;
/** Spherical Linear Interpolation.
As t goes from 0 to 1, the Quat object goes from "from" to "to". */
void slerp ( const float t, const Quat& from, const Quat& to);
/** Set quaternion to be equivalent to specified matrix.*/
void set( const osg::Matrix& m );
/** 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
}
}; // end of class prototype
}; // end of namespace
#endif

103
include/osg/Referenced Normal file
View File

@@ -0,0 +1,103 @@
#ifndef OSG_REFERENCED
#define OSG_REFERENCED 1
#include <osg/Export>
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
{
public:
Referenced() { _refCount=0; }
Referenced(Referenced&) { _refCount=0; }
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; }
/** 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; }
/** return the number pointers currently referencing this object. */
int referenceCount() { return _refCount; }
protected:
virtual ~Referenced() {};
int _refCount;
};
};
#endif

168
include/osg/Registry Normal file
View File

@@ -0,0 +1,168 @@
#ifndef OSG_REGISTRY
#define OSG_REGISTRY 1
#include <vector>
#include <string>
#include <osg/Referenced>
#include <osg/DynamicLibrary>
namespace osg {
// forward declare referenced classes to help avoid mutiple includes
class Object;
class Image;
class Node;
class Input;
SG_EXPORT extern Object* loadObjectFile(const char *name);
SG_EXPORT extern Image* loadImageFile(const char *name);
SG_EXPORT extern Node* loadNodeFile(const char *name);
SG_EXPORT extern bool saveObjectFile(Object& object, const char *name);
SG_EXPORT extern bool saveImageFile(Image& image, const char *name);
SG_EXPORT extern bool saveNodeFile(Node& node, const char *name);
/** pure virtual base class for reading and writing of non native formats. */
class SG_EXPORT ReaderWriter : public Referenced
{
public:
virtual ~ReaderWriter() {}
virtual const char* className() = 0;
virtual bool acceptsExtension(const std::string& /*extension*/) { return false; }
virtual Object* readObject(const std::string& /*fileName*/) { return NULL; }
virtual Image* readImage(const std::string& /*fileName*/) { return NULL; }
virtual Node* readNode(const std::string& /*fileName*/) { return NULL; }
virtual bool writeObject(Object& /*obj*/,const std::string& /*fileName*/) {return false; }
virtual bool writeImage(Image& /*image*/,const std::string& /*fileName*/) {return false; }
virtual bool writeNode(Node& /*node*/,const std::string& /*fileName*/) { return false; }
};
/**
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 defined in Object.h can be
used to automatically register at runtime a Object
with the Registry.
The RegisterReaderWriterProxy defined in ReaderWriter.h can
be used to automatically register at runtime a reader/writer
with the Registry.
*/
class SG_EXPORT Registry
{
public:
~Registry();
static Registry* instance();
void addPrototype(Object* obj);
void removePrototype(Object* obj);
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);
Object* readObject(Input& fr);
Object* readObject(const std::string& fileName);
bool writeObject(Object& obj, const std::string& fileName);
Image* readImage(Input& fr);
Image* readImage(const std::string& fileName);
bool writeImage(Image& obj, const std::string& fileName);
Node* readNode(Input& fr);
Node* readNode(const std::string& fileName);
bool writeNode(Node& node, const std::string& fileName);
private:
typedef std::vector<ref_ptr<Object> > PrototypeList;
typedef std::vector<ref_ptr<ReaderWriter> > ReaderWriterList;
typedef std::vector<ref_ptr<DynamicLibrary> > DynamicLibraryList;
/** 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);
PrototypeList _protoList;
ReaderWriterList _rwList;
DynamicLibraryList _dlList;
std::vector<int> _nodeProtoList;
std::vector<int> _imageProtoList;
bool _openingLibrary;
};
/** Proxy class for automatic registration of reader/writers with the
Registry.*/
template<class T>
class RegisterObjectProxy
{
public:
RegisterObjectProxy()
{
_obj = new T;
_obj->ref();
Registry::instance()->addPrototype(_obj);
}
~RegisterObjectProxy()
{
Registry::instance()->removePrototype(_obj);
_obj->unref();
}
protected:
T* _obj;
};
/** Proxy class for automatic registration of reader/writers with the
Registry.*/
template<class T>
class RegisterReaderWriterProxy
{
public:
RegisterReaderWriterProxy()
{
_rw = new T;
_rw->ref();
Registry::instance()->addReaderWriter(_rw);
}
~RegisterReaderWriterProxy()
{
Registry::instance()->removeReaderWriter(_rw);
_rw->unref();
}
protected:
T* _rw;
};
};
#endif // __SG_OBJECT_FACTORY_H

39
include/osg/Scene Normal file
View File

@@ -0,0 +1,39 @@
#ifndef OSG_SCENE
#define OSG_SCENE 1
#include <osg/Group>
#include <osg/GeoState>
namespace osg {
/** The top level group node in a scene graph. */
class SG_EXPORT Scene : public Group
{
public :
Scene();
virtual Object* clone() const { return new Scene(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<Scene*>(obj)!=NULL; }
virtual const char* className() const { return "Scene"; }
virtual void accept(NodeVisitor& nv) { nv.apply(*this); }
/** set the scene's GeoState.*/
void setGState(osg::GeoState* gstate);
/** return the scene's GeoState.*/
osg::GeoState* getGState() { return _gstate; }
protected :
virtual ~Scene();
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
osg::GeoState* _gstate;
};
};
#endif

63
include/osg/Seg Normal file
View File

@@ -0,0 +1,63 @@
#ifndef OSG_SEG
#define OSG_SEG 1
#include <osg/Vec3>
#include <osg/Types>
#include <osg/Matrix>
#include <osg/Referenced>
#include <osg/BoundingBox>
#include <osg/BoundingSphere>
namespace osg {
/** Segment class for representing a line segment.*/
class SG_EXPORT Seg : public Referenced
{
public:
Seg() {};
Seg(const Seg& seg) : Referenced(),_s(seg._s),_e(seg._e) {}
Seg(const Vec3& s,const Vec3& e) : _s(s),_e(e) {}
virtual ~Seg() {}
Seg& operator = (const Seg& seg) { _s = seg._s; _e = seg._e; return *this; }
void set(const Vec3& s,const Vec3& e) { _s=s; _e=e; }
const Vec3& start() const { return _s; }
Vec3& start() { return _s; }
const Vec3& end() const { return _e; }
Vec3& end() { return _e; }
/** return true if segment intersects BoundingBox.*/
bool intersect(const BoundingBox& bb) const;
/** return true if segment intersects BoundingSphere and return the intersection ratio's.*/
bool intersect(const BoundingBox& bb,float& r1,float& r2) const;
/** return true if segment intersects BoundingSphere.*/
bool intersect(const BoundingSphere& bs) const;
/** return true if segment intersects BoundingSphere and return the intersection ratio's.*/
bool intersect(const BoundingSphere& bs,float& r1,float& r2) const;
/** return true if segment intersects triangle and set ratio long segment. */
bool intersect(const Vec3& v1,const Vec3& v2,const Vec3& v3,float& r);
/** post multiply a segment by matrix.*/
void mult(const Seg& seg,const Matrix& m) { _s = seg._s*m; _e = seg._e*m; }
/** pre multiply a segment by matrix.*/
void mult(const Matrix& m,const Seg& seg) { _s = m*seg._s; _e = m*seg._e; }
protected:
static bool intersectAndClip(Vec3& s,Vec3& e,const BoundingBox& bb);
Vec3 _s;
Vec3 _e;
};
};
#endif

28
include/osg/Sequence Normal file
View File

@@ -0,0 +1,28 @@
#ifndef OSG_SEQUENCE
#define OSG_SEQUENCE 1
#include <osg/Switch>
namespace osg {
/** Sequence - Switch node which allows iterators between children.
Note: has not been implemented yet!
*/
class SG_EXPORT Sequence : public Group
{
public :
Sequence() {}
virtual Object* clone() const { return new Sequence(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<Sequence*>(obj)!=NULL; }
virtual const char* className() const { return "Sequence"; }
virtual void accept(NodeVisitor& nv) { nv.apply(*this); }
protected :
virtual ~Sequence() {}
};
};
#endif

22
include/osg/State Normal file
View File

@@ -0,0 +1,22 @@
#ifndef OSG_STATE
#define OSG_STATE 1
#include <osg/Export>
namespace osg {
class SG_EXPORT State
{
public :
State( void );
~State( void );
private :
GeoState *initial;
GeoState *req;
GeoState *current;
};
};
#endif

45
include/osg/Switch Normal file
View File

@@ -0,0 +1,45 @@
#ifndef OSG_SWITCH
#define OSG_SWITCH 1
#include <osg/Group>
namespace osg {
/** Switch - 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.
*/
class SG_EXPORT Switch : public Group
{
public :
enum SwitchType {
ALL_CHILDREN_ON=-1,
ALL_CHILDREN_OFF=-2
};
Switch();
virtual Object* clone() const { return new Switch(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<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; }
protected :
virtual ~Switch() {}
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
int _value;
};
};
#endif

45
include/osg/TexEnv Normal file
View File

@@ -0,0 +1,45 @@
#ifndef OSG_TEXENV
#define OSG_TEXENV 1
#include <osg/Export>
#include <osg/GL>
#include <osg/Object>
namespace osg {
class SG_EXPORT TexEnv : public Object
{
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 const char* className() const { return "TexEnv"; }
void setMode( TexEnvMode mode );
void apply( void );
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;
};
};
#endif

54
include/osg/TexGen Normal file
View File

@@ -0,0 +1,54 @@
#ifndef OSG_TEXGEN
#define OSG_TEXGEN 1
#include <osg/Export>
#include <osg/GL>
#include <osg/OSG>
#include <osg/Object>
namespace osg {
class Input;
class Output;
class SG_EXPORT TexGen : public Object
{
public :
enum TexGenMode {
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"; }
static void enable( void );
static void disable( void );
void apply( void );
void setMode( TexGenMode mode ) { _mode = mode; }
protected :
virtual ~TexGen( void );
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
bool matchModeStr(const char* str,TexGenMode& mode);
const char* getModeStr(TexGenMode mode);
TexGenMode _mode;
};
};
#endif

29
include/osg/TexMat Normal file
View File

@@ -0,0 +1,29 @@
#ifndef OSG_TEXMAT
#define OSG_TEXMAT 1
#include <osg/Export>
#include <osg/Matrix>
namespace osg {
class SG_EXPORT TexMat : public Matrix
{
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 const char* className() const { return "TexMat"; }
void apply( void );
protected:
virtual ~TexMat( void );
};
};
#endif

104
include/osg/Texture Normal file
View File

@@ -0,0 +1,104 @@
#ifndef OSG_TEXTURE
#define OSG_TEXTURE 1
#include <osg/Export>
#include <osg/GL>
#include <osg/OSG>
#include <osg/Image>
namespace osg {
class Input;
class Output;
/** Texture state class which encapsulates OpenGl texture functionality.*/
class SG_EXPORT Texture : public Object
{
public :
Texture();
static Texture* instance();
virtual Object* clone() const { return new Texture(); }
virtual bool isSameKindAs(Object* obj) { return dynamic_cast<Texture*>(obj)!=NULL; }
virtual const char* className() const { return "Texture"; }
/** Set the texture image. */
void setImage(Image* image);
/** Get the texture image. */
Image* getImage() const { return _image.get(); }
enum WrapParameter {
WRAP_S,
WRAP_T,
WRAP_R
};
enum WrapMode {
CLAMP = GL_CLAMP,
REPEAT = GL_REPEAT
};
/** Set the texture wrap mode.*/
void setWrap(WrapParameter which, WrapMode wrap);
/** Get the texture wrap mode.*/
WrapMode getWrap(WrapParameter which) const;
enum FilterParameter {
MIN_FILTER,
MAG_FILTER
};
enum FilterMode {
LINEAR = GL_LINEAR,
LINEAR_MIPMAP_LINEAR = GL_LINEAR_MIPMAP_LINEAR,
LINEAR_MIPMAP_NEAREST = GL_LINEAR_MIPMAP_NEAREST,
NEAREST = GL_NEAREST,
NEAREST_MIPMAP_LINEAR = GL_NEAREST_MIPMAP_LINEAR,
NEAREST_MIPMAP_NEAREST = GL_NEAREST_MIPMAP_NEAREST
};
/** Set the texture filter mode.*/
void setFilter(FilterParameter which, FilterMode filter);
/** Get the texture filter mode.*/
FilterMode getFilter(FilterParameter which) const;
/** Enable OpenGL texturing.*/
static void enable( void );
/** Disable OpenGL texturing.*/
static void disable( void );
/** On first apply, create the minmapped texture and bind it,
subsequent apply will simple bind to texture.*/
void apply( void );
protected :
virtual ~Texture();
virtual bool readLocalData(Input& fr);
virtual bool writeLocalData(Output& fw);
uint _handle;
ref_ptr<Image> _image;
bool matchWrapStr(const char* str,WrapMode& wrap);
const char* getWrapStr(WrapMode wrap);
bool matchFilterStr(const char* str,FilterMode& filter);
const char* getFilterStr(FilterMode filter);
WrapMode _wrap_s;
WrapMode _wrap_t;
WrapMode _wrap_r;
FilterMode _min_filter;
FilterMode _mag_filter;
};
};
#endif

77
include/osg/Timer Normal file
View File

@@ -0,0 +1,77 @@
#ifndef OSG_TIMER
#define OSG_TIMER 1
#include <osg/Export>
namespace osg {
#ifdef WIN32
typedef __int64 Timer_t;
#else
typedef unsigned long long Timer_t;
#endif
class SG_EXPORT Timer {
public:
Timer( void );
~Timer( void );
#ifdef WIN32
#pragma optimize("",off)
inline Timer_t tick( void )
{
volatile Timer_t ts;
volatile unsigned int HighPart;
volatile unsigned int LowPart;
_asm
{
xor eax, eax // Used when QueryPerformanceCounter()
xor edx, edx // not supported or minimal overhead
_emit 0x0f // desired
_emit 0x31 //
mov HighPart,edx
mov LowPart,eax
}
//ts = LowPart | HighPart >> 32;
*((unsigned int*)&ts) = LowPart;
*((unsigned int*)&ts+1) = HighPart;
return ts;
}
#pragma optimize("",on)
#endif
#ifdef __linux
#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
double delta_s( Timer_t t1, Timer_t t2 );
double delta_m( Timer_t t1, Timer_t t2 );
Timer_t delta_u( Timer_t t1, Timer_t t2 );
Timer_t delta_n( Timer_t t1, Timer_t t2 );
private :
double microseconds_per_click;
double nanoseconds_per_click;
unsigned long *clk;
int cycleCntrSize;
static unsigned long dummy;
static int inited;
static double cpu_mhz;
void init( void );
};
};
#endif

50
include/osg/Transparency Normal file
View File

@@ -0,0 +1,50 @@
#ifndef OSG_TRANSPARENCY
#define OSG_TRANSPARENCY 1
#include <osg/Export>
#include <osg/Object>
#include <osg/GL>
namespace osg {
class SG_EXPORT Transparency : public Object
{
public :
enum TransparencyMode {
DST_ALPHA = GL_DST_ALPHA,
DST_COLOR = GL_DST_COLOR,
ONE = GL_ONE,
ONE_MINUS_DST_ALPHA = GL_ONE_MINUS_DST_ALPHA,
ONE_MINUS_DST_COLOR = GL_ONE_MINUS_DST_COLOR,
ONE_MINUS_SRC_ALPHA = GL_ONE_MINUS_SRC_ALPHA,
ONE_MINUS_SRC_COLOR = GL_ONE_MINUS_SRC_COLOR,
SRC_ALPHA = GL_SRC_ALPHA,
SRC_ALPHA_SATURATE = GL_SRC_ALPHA_SATURATE,
SRC_COLOR = GL_SRC_COLOR,
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"; }
void setFunction( int source, int destination );
static void enable( void );
static void disable( void );
void apply( void );
protected :
virtual ~Transparency();
int _source_factor;
int _destination_factor;
};
};
#endif

32
include/osg/Types Normal file
View File

@@ -0,0 +1,32 @@
#ifndef OSG_TYPES
#define OSG_TYPES 1
#include <osg/Export>
#include <osg/Vec3>
namespace osg {
typedef unsigned int uint;
typedef unsigned short ushort;
typedef unsigned char uchar;
typedef uchar ubyte;
#ifdef WIN32
#define M_E 2.7182818284590452354
#define M_LOG2E 1.4426950408889634074
#define M_LOG10E 0.43429448190325182765
#define M_LN2 0.69314718055994530942
#define M_LN10 2.30258509299404568402
#define M_PI 3.14159265358979323846
#define M_PI_2 1.57079632679489661923
#define M_PI_4 0.78539816339744830962
#define M_1_PI 0.31830988618379067154
#define M_2_PI 0.63661977236758134308
#define M_2_SQRTPI 1.12837916709551257390
#define M_SQRT2 1.41421356237309504880
#define M_SQRT1_2 0.70710678118654752440
#endif
};
#endif

149
include/osg/Vec2 Normal file
View File

@@ -0,0 +1,149 @@
#ifndef OSG_VEC2
#define OSG_VEC2 1
#include <osg/Export>
#include <math.h>
#ifdef OSG_USE_IO_DOT_H
#include <iostream.h>
#else
#include <iostream>
using namespace std;
#endif
namespace osg {
/** General purpose float pair, uses include representation of
texture coordinates.
No support yet added for float * Vec2 - is it necessary?
Need to define a non-member non-friend operator* etc.
BTW: Vec2 * float is okay
*/
class Vec2
{
public:
Vec2() {} // no operations done to maintain speed
Vec2(float x,float y) { _v[0]=x; _v[1]=y; }
float _v[2];
bool operator == (const Vec2& v) const { return _v[0]==v._v[0] && _v[1]==v._v[1]; }
inline float* ptr() { return _v; }
inline const float* ptr() const { return _v; }
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 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]; }
/// dot product
inline 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
{
return Vec2(_v[0]*rhs, _v[1]*rhs);
}
/// unary multiply by scalar
inline Vec2& operator *= (const float& rhs)
{
_v[0]*=rhs;
_v[1]*=rhs;
return *this;
}
/// divide by scalar
inline Vec2 operator / (const float& rhs) const
{
return Vec2(_v[0]/rhs, _v[1]/rhs);
}
/// unary divide by scalar
inline Vec2& operator /= (const float& rhs)
{
_v[0]/=rhs;
_v[1]/=rhs;
return *this;
}
/// binary vector add
inline Vec2 operator + (const Vec2& rhs) const
{
return Vec2(_v[0]+rhs._v[0], _v[1]+rhs._v[1]);
}
/** unary vector add. Slightly more efficient because no temporary
intermediate object.*/
inline Vec2& operator += (const Vec2& rhs)
{
_v[0] += rhs._v[0];
_v[1] += rhs._v[1];
return *this;
}
/// binary vector subract
inline Vec2 operator - (const Vec2& rhs) const
{
return Vec2(_v[0]-rhs._v[0], _v[1]-rhs._v[1]);
}
/// unary vector subract
inline Vec2& operator -= (const Vec2& rhs)
{
_v[0]-=rhs._v[0];
_v[1]-=rhs._v[1];
return *this;
}
/// negation operator. Returns the negative of the Vec2
inline Vec2 operator - () const
{
return Vec2 (-_v[0], -_v[1]);
}
/// Length of the vector = sqrt( vec . vec )
inline 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
{
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()
{
float norm = Vec2::length();
_v[0] /= norm;
_v[1] /= norm;
return( norm );
}
friend inline ostream& operator << (ostream& output, const Vec2& vec)
{
output << vec._v[0] << " "
<< vec._v[1];
return output; // to enable cascading
}
}; // end of class Vec2
} // end of namespace osg
#endif

168
include/osg/Vec3 Normal file
View File

@@ -0,0 +1,168 @@
#ifndef OSG_VEC3
#define OSG_VEC3 1
#include <osg/Export>
#include <math.h>
#ifdef OSG_USE_IO_DOT_H
#include <iostream.h>
#else
#include <iostream>
using namespace std;
#endif
namespace osg {
/** General purpose float triple for use as vertices, vectors and normals.
Provides general maths operations from addition through to cross products.
No support yet added for float * Vec3 - is it necessary?
Need to define a non-member non-friend operator* etc.
Vec3 * float is okay
*/
class Vec3
{
public:
Vec3() {} // no operations done to maintain speed
Vec3(float x,float y,float z) { _v[0]=x; _v[1]=y; _v[2]=z; }
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 float* ptr() { return _v; }
inline const float* ptr() const { return _v; }
inline void set( float x, float y, float z)
{
_v[0]=x; _v[1]=y; _v[2]=z;
}
inline float& operator [] (int i) { return _v[i]; }
inline 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]; }
/// dot product
inline float operator * (const Vec3& rhs) const
{
return _v[0]*rhs._v[0]+_v[1]*rhs._v[1]+_v[2]*rhs._v[2];
}
/// cross product
inline 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] ,
_v[0]*rhs._v[1]-_v[1]*rhs._v[0]);
}
/// multiply by scalar
inline Vec3 operator * (const float& rhs) const
{
return Vec3(_v[0]*rhs, _v[1]*rhs, _v[2]*rhs);
}
/// unary multiply by scalar
inline Vec3& operator *= (const float& rhs)
{
_v[0]*=rhs;
_v[1]*=rhs;
_v[2]*=rhs;
return *this;
}
/// divide by scalar
inline Vec3 operator / (const float& rhs) const
{
return Vec3(_v[0]/rhs, _v[1]/rhs, _v[2]/rhs);
}
/// unary divide by scalar
inline Vec3& operator /= (const float& rhs)
{
_v[0]/=rhs;
_v[1]/=rhs;
_v[2]/=rhs;
return *this;
}
/// binary vector add
inline Vec3 operator + (const Vec3& rhs) const
{
return Vec3(_v[0]+rhs._v[0], _v[1]+rhs._v[1], _v[2]+rhs._v[2]);
}
/** unary vector add. Slightly more efficient because no temporary
intermediate object*/
inline Vec3& operator += (const Vec3& rhs)
{
_v[0] += rhs._v[0];
_v[1] += rhs._v[1];
_v[2] += rhs._v[2];
return *this;
}
/// binary vector subract
inline Vec3 operator - (const Vec3& rhs) const
{
return Vec3(_v[0]-rhs._v[0], _v[1]-rhs._v[1], _v[2]-rhs._v[2]);
}
/// unary vector subract
inline Vec3& operator -= (const Vec3& rhs)
{
_v[0]-=rhs._v[0];
_v[1]-=rhs._v[1];
_v[2]-=rhs._v[2];
return *this;
}
/// negation operator. Returns the negative of the Vec3
inline Vec3 operator - () const
{
return Vec3 (-_v[0], -_v[1], -_v[2]);
}
/// Length of the vector = sqrt( vec . vec )
inline float length( void ) 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
{
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()
{
float norm = Vec3::length();
_v[0] /= norm;
_v[1] /= norm;
_v[2] /= norm;
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
}
}; // end of class Vec3
} // end of namespace osg
#endif

178
include/osg/Vec4 Normal file
View File

@@ -0,0 +1,178 @@
#ifndef OSG_VEC4
#define OSG_VEC4 1
#include <osg/Export>
#include <math.h>
#ifdef OSG_USE_IO_DOT_H
#include <iostream.h>
#else
#include <iostream>
using namespace std;
#endif
namespace osg {
/** General purpose float quad, uses include representation
of colour coordinates.
No support yet added for float * Vec4 - is it necessary?
Need to define a non-member non-friend operator* etc.
Vec4 * float is okay
*/
class Vec4
{
public:
// Methods are defined here so that they are implicitly inlined
Vec4() {} // no operations done to maintain speed
Vec4(float x, float y, float z, float w)
{
_v[0]=x; _v[1]=y; _v[2]=z; _v[3]=w;
}
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 float* ptr() { return _v; }
inline const float* ptr() const { return _v; }
inline void set( float x, float y, float z, float w)
{
_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& x() { return _v[0]; }
inline float& y() { return _v[1]; }
inline float& z() { return _v[2]; }
inline float& w() { return _v[3]; }
inline float x() const { return _v[0]; }
inline float y() const { return _v[1]; }
inline float z() const { return _v[2]; }
inline float w() const { return _v[3]; }
/// dot product
inline float operator * (const Vec4& rhs) const
{
return _v[0]*rhs._v[0]+
_v[1]*rhs._v[1]+
_v[2]*rhs._v[2]+
_v[3]*rhs._v[3] ;
}
/// multiply by scalar
inline Vec4 operator * (const float& rhs) const
{
return Vec4(_v[0]*rhs, _v[1]*rhs, _v[2]*rhs, _v[3]*rhs);
}
/// unary multiply by scalar
inline Vec4& operator *= (const float& rhs)
{
_v[0]*=rhs;
_v[1]*=rhs;
_v[2]*=rhs;
_v[3]*=rhs;
return *this;
}
/// divide by scalar
inline Vec4 operator / (const float& rhs) const
{
return Vec4(_v[0]/rhs, _v[1]/rhs, _v[2]/rhs, _v[3]/rhs);
}
/// unary divide by scalar
inline Vec4& operator /= (const float& rhs)
{
_v[0]/=rhs;
_v[1]/=rhs;
_v[2]/=rhs;
_v[3]/=rhs;
return *this;
}
/// binary vector add
inline Vec4 operator + (const Vec4& rhs) const
{
return Vec4(_v[0]+rhs._v[0], _v[1]+rhs._v[1],
_v[2]+rhs._v[2], _v[3]+rhs._v[3]);
}
/** unary vector add. Slightly more efficient because no temporary
intermediate object*/
inline Vec4& operator += (const Vec4& rhs)
{
_v[0] += rhs._v[0];
_v[1] += rhs._v[1];
_v[2] += rhs._v[2];
_v[3] += rhs._v[3];
return *this;
}
/// binary vector subract
inline Vec4 operator - (const Vec4& rhs) const
{
return Vec4(_v[0]-rhs._v[0], _v[1]-rhs._v[1],
_v[2]-rhs._v[2], _v[3]-rhs._v[3] );
}
/// unary vector subract
inline Vec4& operator -= (const Vec4& rhs)
{
_v[0]-=rhs._v[0];
_v[1]-=rhs._v[1];
_v[2]-=rhs._v[2];
_v[3]-=rhs._v[3];
return *this;
}
/// negation operator. Returns the negative of the Vec4
inline 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
{
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
{
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()
{
float norm = Vec4::length();
_v[0] /= norm;
_v[1] /= norm;
_v[2] /= norm;
_v[3] /= norm;
return( norm );
}
friend inline ostream& operator << (ostream& output, const Vec4& vec)
{
output << vec._v[0] << " "
<< vec._v[1] << " "
<< vec._v[2] << " "
<< vec._v[3];
return output; // to enable cascading
}
}; // end of class Vec4
} // end of namespace osg
#endif

33
include/osg/Version Normal file
View File

@@ -0,0 +1,33 @@
#ifndef OSG_VERSION
#define OSG_VERSION 1
#include <osg/Export>
extern "C" {
/**
* getVersion_osg() 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, osgGetVersion, ,
[AC_MSG_ERROR(OpenSceneGraph library not found. See http://www.openscenegraph.org)],)
\endverbatim
*/
extern SG_EXPORT const char* osgGetVersion();
/**
* getLibraryName_osg() returns the library name in human friendly form.
*/
extern SG_EXPORT const char* osgGetLibraryName();
};
#endif

22
include/osgGLUT/Export Normal file
View File

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

View File

@@ -0,0 +1,108 @@
#ifndef OSGGLUT_GLUTEVENTADAPTER
#define OSGGLUT_GLUTEVENTADAPTER 1
#include <osgUtil/GUIEventAdapter>
#include <osgGLUT/Export>
namespace osgGLUT{
/** Class for adapting GLUT events so that they can be used as input to osgUtil::CameraManipulators.*/
class OSGGLUT_EXPORT GLUTEventAdapter : public osgUtil::GUIEventAdapter
{
public:
GLUTEventAdapter();
virtual ~GLUTEventAdapter() {}
/** 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,int button, int state, int x, int y);
/** 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;
};
}
#endif

35
include/osgGLUT/Version Executable file
View File

@@ -0,0 +1,35 @@
#ifndef OSGGLUT_VERSION
#define OSGGLUT_VERSION 1
#include <osgGLUT/Export>
extern "C" {
/**
* getVersion_osgGLUT() returns the library version number.
* Numbering conventon : osg_src-0.8-31 will return 0.8.31 from getVersion_osgGLUT.
*
* 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) GLUT library
#
AC_CHECK_LIB(osg, osgGLUTGetVersion, ,
[AC_MSG_ERROR(OpenSceneGraph GLUT library not found. See http://www.openscenegraph.org)],)
\endverbatim
*/
extern OSGGLUT_EXPORT const char* osgGLUTGetVersion();
/**
* getLibraryName_osgGLUT() returns the library name in human friendly form.
*/
extern OSGGLUT_EXPORT const char* osgGLUTGetLibraryName();
};
#endif

147
include/osgGLUT/Viewer Normal file
View File

@@ -0,0 +1,147 @@
#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>
#include <osgUtil/GUIEventAdapter>
#include <osgUtil/CameraManipulator>
#include <osgUtil/SceneView>
#include <osgGLUT/Export>
#ifdef SGV_USE_RTFS
#include <rtfs/rtfs.h>
#endif
#include <string>
#ifdef OSG_USE_IO_DOT_H
#include <iostream.h>
#else
#include <iostream>
using namespace std;
#endif
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.
* Someone please rewrite it :-)
*/
class OSGGLUT_EXPORT Viewer : public osgUtil::GUIActionAdapter
{
public:
Viewer();
virtual ~Viewer();
virtual bool init( osg::Node* );
virtual bool run();
// called on each frame redraw..
virtual bool update();
virtual bool traverse();
virtual bool draw();
// initialize the clock.
long initClock();
// time since initClock() in seconds.
float clockSeconds() { return _timer.delta_s(_initialTick,clockTick()); }
// update the number of ticks since the last frame update.
osg::Timer_t updateFrameTick();
// time from the current frame update and the previous one in seconds.
float frameSeconds() { return _timer.delta_s(_lastFrameTick,_frameTick); }
float frameRate() { return 1.0f/frameSeconds(); }
void help(ostream& fout);
// hande multiple camera.
void registerCameraManipulator(osgUtil::CameraManipulator* cm);
void selectCameraManipulator(unsigned int pos);
// 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);
protected:
static void displayCB();
static void reshapeCB(GLint w, GLint h);
static void visibilityCB(int state);
static void mouseMotionCB(int x, int y);
static void mousePassiveMotionCB(int x, int y);
static void mouseCB(int button, int state, int x, int y);
static void keyboardCB(unsigned char key, int x, int y );
virtual void display();
virtual void reshape(GLint w, GLint h);
virtual void visibility(int state);
virtual void mouseMotion(int x, int y);
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);
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;
std::string _saveFileName;
int ww, wh;
#ifdef SGV_USE_RTFS
unsigned int frame_rate;
RTfs *fs;
#endif
bool _viewFrustumCullingActive;
bool _smallFeatureCullingActive;
int mx, my, mbutton;
int polymode;
int texture;
int backface;
int lighting;
int flat_shade;
int _two_sided_lighting;
bool fullscreen;
int _saved_ww,_saved_wh;
bool _printStats;
bool _useDisplayLists;
osg::Timer _timer;
osg::Timer_t _tickRatePerSecond;
osg::Timer_t _initialTick;
osg::Timer_t _lastFrameTick;
osg::Timer_t _frameTick;
// system tick.
osg::Timer_t clockTick();
osg::Timer_t frameTick();
};
}
#endif // SG_VIEWIER_H

View File

@@ -0,0 +1,55 @@
#ifndef OSGUTIL_CAMERAMANIPULATOR
#define OSGUTIL_CAMERAMANIPULATOR 1
#include <osg/Referenced>
#include <osg/Camera>
#include <osgUtil/Export>
#include <osgUtil/GUIEventAdapter>
#include <osgUtil/GUIActionAdapter>
namespace osgUtil{
class OSGUTIL_EXPORT CameraManipulator : public osg::Referenced
{
public:
CameraManipulator();
virtual ~CameraManipulator();
/** attach a camera to the manipulator to be used for specifying view.*/
virtual void setCamera(osg::Camera*);
/** get the attached a camera.*/
virtual osg::Camera * getCamera() const;
/** Attach a node to the manipulator.
Automatically detaches previously attached node.
setNode(NULL) detaches previously nodes.
Is ignored by manipulators which do not require a reference model.*/
virtual void setNode(osg::Node*) {}
/** Return node if attached.*/
virtual 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&) {}
/** Start/restart the manipulator.*/
virtual void init(GUIEventAdapter& ,GUIActionAdapter&) {}
/** Handle events, return true if handled, false otherwise.*/
virtual bool update(GUIEventAdapter& ea,GUIActionAdapter& us);
protected:
// Reference pointer to a camera
osg::ref_ptr<osg::Camera> _camera;
};
}
#endif

View File

@@ -0,0 +1,72 @@
#ifndef OSGUTIL_COMPILEGEOSETVISITOR
#define OSGUTIL_COMPILEGEOSETVISITOR 1
#include <osg/NodeVisitor>
#include <osg/Geode>
#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
* 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
* all Geode childern. Note, the visitor must only be used within a valid
* OpenGL context as compile uses OpenGL calls.
* _displayListMode == SWITCH_ON_DISPLAY_LISTS sets the Geode's children with
* gset->setUseDisplayList(true), this method does not directly create display list,
* or uses OpenGL calls so if safe to use before a valid OpenGL context has been set up.
* On the next redraw of the scene, the gset's draw methods will be called
* which then will respond to their _useDisplayList being set by creating display lists
* automatically.
* _displayListMode == SWITCH_OFF_DISPLAY_LISTS sets the Geode's children with
* gset->setUseDisplayList(false), this method does not directly create display list,
* or uses OpenGL calls so if safe to use before a valid OpenGL context has been set up.
*/
class OSGUTIL_EXPORT DisplayListVisitor : public osg::NodeVisitor
{
public:
/** Operation modes of the DisplayListVisitor.*/
enum DisplayListMode
{
SWITCH_ON_AND_COMPILE_DISPLAY_LISTS,
SWITCH_ON_DISPLAY_LISTS,
SWITCH_OFF_DISPLAY_LISTS
};
/** Construct a CompileGeoSetsVisior to traverse all child,
* with set specfied display list mode. Default mode is to
* gset->setUseDisplayList(true).
*/
DisplayListVisitor(DisplayListMode mode=SWITCH_ON_DISPLAY_LISTS);
/** Set the operational mode of how the visitor should set up osg::GeoSet's.*/
void setDisplayListMode(DisplayListMode mode) { _displayListMode = mode; }
/** Get the operational mode.*/
DisplayListMode getDisplayListMode() const { return _displayListMode; }
/** Simply traverse using standard NodeVisitor traverse method.*/
virtual void apply(osg::Node& node)
{
traverse(node);
}
/** For each Geode visited set the display list usage according to the
* _displayListMode.
*/
virtual void apply(osg::Geode& node);
protected:
DisplayListMode _displayListMode;
};
};
#endif

View File

@@ -0,0 +1,68 @@
#ifndef OSGUTIL_DRIVEMANIPULATOR
#define OSGUTIL_DRIVEMANIPULATOR 1
#include <osgUtil/CameraManipulator>
namespace osgUtil{
class OSGUTIL_EXPORT DriveManipulator : public CameraManipulator
{
public:
DriveManipulator();
virtual ~DriveManipulator();
/** Attach a node to the manipulator.
Automatically detaches previously attached node.
setNode(NULL) detaches previously nodes.
Is ignored by manipulators which do not require a reference model.*/
virtual void setNode(osg::Node*);
/** Return node if attached.*/
virtual 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);
/** Start/restart the manipulator.*/
virtual void init(GUIEventAdapter& ea,GUIActionAdapter& us);
/** handle events, return true if handled, false otherwise.*/
virtual bool update(GUIEventAdapter& ea,GUIActionAdapter& us);
private:
/** Reset the internal GUIEvent stack.*/
void flushMouseEventStack();
/** Add the current mouse GUIEvent to internal stack.*/
void addMouseEvent(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<osg::Node> _node;
float _modelScale;
float _velocity;
float _height;
float _buffer;
enum SpeedControlMode {
USE_MOUSE_Y_FOR_SPEED,
USE_MOUSE_BUTTONS_FOR_SPEED
};
SpeedControlMode _speedMode;
};
}
#endif

22
include/osgUtil/Export Normal file
View File

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

View File

@@ -0,0 +1,69 @@
#ifndef OSGUTIL_FLIGHTMANIPULATOR
#define OSGUTIL_FLIGHTMANIPULATOR 1
#include <osgUtil/CameraManipulator>
namespace osgUtil{
class OSGUTIL_EXPORT FlightManipulator : public CameraManipulator
{
public:
FlightManipulator();
virtual ~FlightManipulator();
/** Attach a node to the manipulator.
Automatically detaches previously attached node.
setNode(NULL) detaches previously nodes.
Is ignored by manipulators which do not require a reference model.*/
virtual void setNode(osg::Node*);
/** Return node if attached.*/
virtual 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);
/** Start/restart the manipulator.*/
virtual void init(GUIEventAdapter& ea,GUIActionAdapter& us);
/** handle events, return true if handled, false otherwise.*/
virtual bool update(GUIEventAdapter& ea,GUIActionAdapter& us);
enum YawControlMode {
YAW_AUTOMATICALLY_WHEN_BANKED,
NO_AUTOMATIC_YAW
};
/** Set the yaw control between no yaw and yawing when banked.*/
void setYawControlMode(YawControlMode ycm) { _yawMode = ycm; }
private:
/** Reset the internal GUIEvent stack.*/
void flushMouseEventStack();
/** Add the current mouse GUIEvent to internal stack.*/
void addMouseEvent(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<osg::Node> _node;
float _modelScale;
float _velocity;
YawControlMode _yawMode;
};
}
#endif

View File

@@ -0,0 +1,23 @@
#ifndef OSGUTIL_GUIACTIONADAPTER
#define OSGUTIL_GUIACTIONADAPTER 1
#include <osgUtil/Export>
namespace osgUtil{
/** Pure virtual base class for adapting the GUI actions for use in CameraManipulators.*/
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;
};
}
#endif

View File

@@ -0,0 +1,80 @@
#ifndef OSGUTIL_GUIEVENTADAPTER
#define OSGUTIL_GUIEVENTADAPTER 1
#include <osg/Referenced>
#include <osgUtil/Export>
namespace osgUtil{
/** Pure virtual base class for adapting platform specfic events into
generic keyboard and mouse events. */
class GUIEventAdapter : public osg::Referenced
{
public:
GUIEventAdapter() {}
enum MouseButtonMask {
LEFT_BUTTON=1,
MIDDLE_BUTTON=2,
RIGHT_BUTTON=4
};
enum EventType {
PUSH,
RELEASE,
DRAG,
MOVE,
KEYBOARD,
FRAME,
RESIZE,
NONE
};
/** Get the EventType of the GUI event.*/
virtual EventType getEventType() const = 0;
/** key pressed, return -1 if inapropriate for this event. */
virtual int getKey() const = 0;
/** button pressed/released, return -1 if inappropriate for this event.*/
virtual int getButton() const = 0;
/** window minimum x. */
virtual int getXmin() const = 0;
/** window maximum x. */
virtual int getXmax() const = 0;
/** window minimum y. */
virtual int getYmin() const = 0;
/** window maximum y. */
virtual int getYmax() const = 0;
/** current mouse x position.*/
virtual int getX() const = 0;
/** current mouse y position.*/
virtual int getY() const = 0;
/** current mouse button state */
virtual unsigned int getButtonMask() const = 0;
/** time in seconds of event. */
virtual float time() const = 0;
protected:
/** Force users to create on heap, so that mulitple referencing is safe.*/
virtual ~GUIEventAdapter() {}
};
}
#endif

View File

@@ -0,0 +1,142 @@
#ifndef OSGUTIL_INTERSECTVISITOR
#define OSGUTIL_INTERSECTVISITOR 1
#include <osg/NodeVisitor>
#include <osg/Seg>
#include <osg/Geode>
#include <osg/Matrix>
#include <osgUtil/Export>
#include <map>
#include <set>
#include <vector>
namespace osgUtil {
class OSGUTIL_EXPORT IntersectState : public osg::Referenced
{
public:
IntersectState();
osg::Matrix* _matrix;
osg::Matrix* _inverse;
typedef std::vector< std::pair<osg::Seg*,osg::Seg*> > SegList;
SegList _segList;
typedef unsigned int SegmentMask;
typedef std::vector<SegmentMask> SegmentMaskStack;
SegmentMaskStack _segmentMaskStack;
bool isCulled(const osg::BoundingSphere& bs,SegmentMask& segMaskOut);
bool isCulled(const osg::BoundingBox& bb,SegmentMask& segMaskOut);
protected:
~IntersectState();
};
class OSGUTIL_EXPORT Hit : public osg::Referenced
{
public:
Hit();
Hit(const Hit& hit);
~Hit();
Hit& operator = (const Hit& hit);
typedef std::vector<int> VecIndexList;
bool operator < (const Hit& hit) const
{
if (_originalSeg<hit._originalSeg) return true;
if (_originalSeg>hit._originalSeg) return false;
return _ratio<hit._ratio;
}
float _ratio;
osg::Seg* _originalSeg;
osg::Seg* _localSeg;
osg::NodePath _nodePath;
osg::Geode* _geode;
osg::GeoSet* _geoset;
osg::Matrix* _matrix;
VecIndexList _vecIndexList;
int _primitiveIndex;
osg::Vec3 _intersectPoint;
osg::Vec3 _intersectNormal;
};
/** Basic visitor for ray based collisions of a scene.
Note, still in development, current version has not
pratical functionality!*/
class OSGUTIL_EXPORT IntersectVisitor : public osg::NodeVisitor
{
public:
IntersectVisitor();
virtual ~IntersectVisitor();
void reset();
/** Add a line segment to use for intersection testing during scene traversal.*/
void addSeg(osg::Seg* seg);
/** Modes to control how IntersectVisitor reports hits. */
enum HitReportingMode {
ONLY_NEAREST_HIT,
ALL_HITS
};
/** Set the mode of how hits should reported back from a traversal.*/
void setHitReportingMode(HitReportingMode hrm) { _hitReportingMode = hrm; }
/** Get the mode of how hits should reported back from a traversal.*/
HitReportingMode getHitReportingMode() { return _hitReportingMode; }
//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(); }
bool hits();
virtual void apply(osg::Node&);
virtual void apply(osg::Geode& node);
virtual void apply(osg::Billboard& node);
virtual void apply(osg::Group& node);
virtual void apply(osg::DCS& node);
virtual void apply(osg::Switch& node);
virtual void apply(osg::LOD& node);
virtual void apply(osg::Scene& node);
protected:
bool intersect(osg::GeoSet& gset);
void pushMatrix(const osg::Matrix& matrix);
void popMatrix();
bool enterNode(osg::Node& node);
void leaveNode();
typedef std::vector<IntersectState*> IntersectStateStack;
IntersectStateStack _intersectStateStack;
osg::NodePath _nodePath;
HitReportingMode _hitReportingMode;
SegHitListMap _segHitList;
};
};
#endif

View File

@@ -0,0 +1,196 @@
#ifndef OSGUTIL_RENDERVISITOR
#define OSGUTIL_RENDERVISITOR 1
#include <osg/NodeVisitor>
#include <osg/BoundingSphere>
#include <osg/BoundingBox>
#include <osg/Matrix>
#include <osg/GeoSet>
#include <osg/GeoState>
#include <osg/Camera>
#include <osgUtil/Export>
#include <map>
#include <vector>
namespace osgUtil {
/** Container class for encapsulating the viewing state in local
coordinates, during the cull traversal.
*/
class OSGUTIL_EXPORT ViewState : public osg::Referenced
{
public:
ViewState();
osg::Matrix* _matrix;
osg::Matrix* _inverse;
osg::Vec3 _eyePoint;
osg::Vec3 _centerPoint;
osg::Vec3 _lookVector;
osg::Vec3 _upVector;
osg::Vec3 _frustumTopNormal;
osg::Vec3 _frustumBottomNormal;
osg::Vec3 _frustumLeftNormal;
osg::Vec3 _frustumRightNormal;
float _ratio;
bool _viewFrustumCullingActive;
bool _smallFeatureCullingActive;
bool isCulled(const osg::BoundingSphere& sp);
bool isCulled(const osg::BoundingBox& bb);
protected:
~ViewState();
};
/**
* Basic NodeVisitor implementation for rendering a scene.
* This visitor traverses the scene graph, collecting transparent and
* opaque osg::GeoSets into a depth sorted transparent bin and a state
* sorted opaque bin. The opaque bin is rendered first, and then the
* transparent bin in rendered in order from the furthest osg::GeoSet
* from the eye to the one nearest the eye.
*/
class OSGUTIL_EXPORT RenderVisitor : public osg::NodeVisitor
{
public:
RenderVisitor();
virtual ~RenderVisitor();
void reset();
virtual void apply(osg::Node&);
virtual void apply(osg::Geode& node);
virtual void apply(osg::Billboard& node);
virtual void apply(osg::LightSource& node);
virtual void apply(osg::Group& node);
virtual void apply(osg::DCS& node);
virtual void apply(osg::Switch& node);
virtual void apply(osg::LOD& node);
virtual void apply(osg::Scene& node);
void setGlobalState(osg::GeoState* global);
void setPerspective(const osg::Camera& camera);
void setPerspective(float fovy,float aspect,float znear,float zfar);
void setLookAt(const osg::Camera& camera);
void setLookAt(const osg::Vec3& eye,const osg::Vec3& center,const osg::Vec3& upVector);
void setLookAt(double eyeX,double eyeY,double eyeZ,
double centerX,double centerY,double centerZ,
double upX,double upY,double upZ);
void setLODBias(float bias) { _LODBias = bias; }
float getLODBias() { return _LODBias; }
enum TransparencySortMode {
LOOK_VECTOR_DISTANCE,
OBJECT_EYE_POINT_DISTANCE
};
void setTransparencySortMode(TransparencySortMode tsm) { _tsm = tsm; }
enum CullingType {
VIEW_FRUSTUM_CULLING,
SMALL_FEATURE_CULLING
};
/**
* Enables/disables the specified culling type.
* @param ct The culling type to enable/disable.
* @param active true enables the culling type, false disables.
*/
void setCullingActive(CullingType ct, bool active);
/**
* Returns the state of the specified culling type.
* @result true, if culling type is enabled, false otherwise.
*/
bool getCullingActive(CullingType ct);
/**
* Calculates the near_plane and the far_plane for the current
* camera view depending on the objects currently stored in the
* opaque and transparent bins.
* @param near_plane reference to a variable that can store the
* near plane result.
* @param far_plane reference to a variable that can store the
* far plane result.
* @result true, if near_plane and far_plane contain valid values,
* false otherwise.
*/
bool calcNearFar(double& near_plane, double& far_plane);
/**
* Renders the osg::GeoSets that were collected in the opaque and
* transparent bins before.
*/
void render();
protected:
void pushMatrix(const osg::Matrix& matrix);
void popMatrix();
osg::Matrix* getCurrentMatrix();
osg::Matrix* getInverseCurrentMatrix();
const osg::Vec3& getEyeLocal();
const osg::Vec3& getCenterLocal();
const osg::Vec3& getLookVectorLocal();
bool _viewFrustumCullingActive;
bool _smallFeatureCullingActive;
bool isCulled(const osg::BoundingSphere& sp);
bool isCulled(const osg::BoundingBox& bb);
typedef std::pair<osg::Matrix*,osg::GeoSet*> MatrixGeoSet;
typedef std::vector<ViewState*> ViewStateStack;
ViewStateStack _viewStateStack;
ViewState* _tvs;
ViewState* _cvs;
typedef std::multimap<osg::GeoState*,MatrixGeoSet> OpaqueList;
typedef std::multimap<float,MatrixGeoSet> TransparentList;
typedef std::map<osg::Matrix*,osg::Light*> LightList;
OpaqueList _opaqueGeoSets;
TransparentList _transparentGeoSets;
LightList _lights;
osg::GeoState* _globalState;
float _LODBias;
float _fovy;
float _aspect;
float _znear;
float _zfar;
void calculateClippingPlanes();
// frustum clipping normals.
osg::Vec3 _frustumTop;
osg::Vec3 _frustumBottom;
osg::Vec3 _frustumLeft;
osg::Vec3 _frustumRight;
TransparencySortMode _tsm;
};
};
#endif

165
include/osgUtil/SceneView Normal file
View File

@@ -0,0 +1,165 @@
#ifndef OSGUTIL_SCENEVIEW
#define OSGUTIL_SCENEVIEW 1
#include <osg/Node>
#include <osg/GeoState>
#include <osg/Light>
#include <osg/Camera>
#include <osgUtil/RenderVisitor>
#include <osgUtil/Export>
namespace osgUtil {
/**
* SceneView is literaly a view of a scene, encapsulating the
* camera, global state, lights and the scene itself. Provides
* methods for setting up the view and rendering it.
*/
class OSGUTIL_EXPORT SceneView : public osg::Referenced
{
public:
/** Constrcut a default scene view.*/
SceneView();
/** Set the data which to view. The data will typically be
* an osg::Scene but can be any osg::Node type.
*/
void setSceneData(osg::Node* node) { _sceneData = node; _need_compile = true;}
/** Get the scene data which to view. The data will typically be
* an osg::Scene but can be any osg::Node type.
*/
osg::Node* getSceneData() { return _sceneData.get(); }
/** Set the viewport of the scene view. */
void setViewport(int x,int y,int width,int height)
{
_view[0] = x;
_view[1] = y;
_view[2] = width;
_view[3] = height;
}
/** Get the viewport of the scene view. */
void getViewport(int& x,int& y,int& width,int& height)
{
x = _view[0];
y = _view[1];
width = _view[2];
height = _view[3];
}
/** Set scene view to use default global state, light, camera
* and render visitor.
*/
void setDefaults();
/** Set the background color used in glClearColor().
Defaults to an off blue color.*/
void setBackgroundColor(const osg::Vec4& color) { _backgroundColor=color; }
/** 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(); }
enum LightingMode {
HEADLIGHT, // default
SKY_LIGHT,
NO_SCENEVIEW_LIGHT
};
void setLightingMode(LightingMode mode) { _lightingMode=mode; }
LightingMode getLightingMode() const { return _lightingMode; }
void setLight(osg::Light* light) { _light = light; }
osg::Light* getLight() const { return _light.get(); }
void setCamera(osg::Camera* camera) { _camera = camera; }
osg::Camera* getCamera() const { return _camera.get(); }
void setRenderVisitor(osgUtil::RenderVisitor* rv) { _renderVisitor = rv; }
osgUtil::RenderVisitor* getRenderVisitor() const { return _renderVisitor.get(); }
void setLODBias(float bias) { _lodBias = bias; }
float getLODBias() const { return _lodBias; }
/** Set to true if you want SceneView to automatically calculate values
for the near/far clipping planes, each frame, set false to use camera's
internal near and far planes. Default value is true.
*/
void setCalcNearFar(bool calc) { _calc_nearfar = calc; }
/** return true if SceneView automatically caclculates near and
far clipping planes for each frame.
*/
bool getCalcNearFar() { return _calc_nearfar; }
/** Calculate, via glUnProject, the object coordinates of a window point.
Note, current implementation requires that SceneView::draw() has been previously called
for projectWindowIntoObject to produce valid values. Consistent with OpenGL
windows coordinates are calculated relative to the bottom left of the window.
Returns true on successful projection.
*/
bool projectWindowIntoObject(const osg::Vec3& window,osg::Vec3& object) const;
/** Calculate, via glUnProject, the object coordinates of a window x,y
when projected onto the near and far planes.
Note, current implementation requires that SceneView::draw() has been previously called
for projectWindowIntoObject to produce valid values. Consistent with OpenGL
windows coordinates are calculated relative to the bottom left of the window.
Returns true on successful projection.
*/
bool projectWindowXYIntoObject(int x,int y,osg::Vec3& near_point,osg::Vec3& far_point) const;
/** Calculate, via glProject, the object coordinates of a window.
Note, current implementation requires that SceneView::draw() has been previously called
for projectWindowIntoObject to produce valid values. Consistent with OpenGL
windows coordinates are calculated relative to the bottom left of the window,
whereas as window API's normally have the top left as the origin,
so you may need to pass in (mouseX,window_height-mouseY,...).
Returns true on successful projection.
*/
bool projectObjectIntoWindow(const osg::Vec3& object,osg::Vec3& window) const;
virtual void cull();
virtual void draw();
protected:
virtual ~SceneView();
osg::ref_ptr<osg::Node> _sceneData;
osg::ref_ptr<osg::GeoState> _globalState;
osg::ref_ptr<osg::Light> _light;
osg::ref_ptr<osg::Camera> _camera;
osg::ref_ptr<osgUtil::RenderVisitor> _renderVisitor;
bool _need_compile;
bool _calc_nearfar;
osg::Vec4 _backgroundColor;
double _near_plane;
double _far_plane;
float _lodBias;
// 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;
};
};
#endif

View File

@@ -0,0 +1,70 @@
#ifndef OSGUTIL_TRACKBALLMANIPULATOR
#define OSGUTIL_TRACKBALLMANIPULATOR 1
#include <osgUtil/CameraManipulator>
namespace osgUtil{
class OSGUTIL_EXPORT TrackballManipulator : public CameraManipulator
{
public:
TrackballManipulator();
virtual ~TrackballManipulator();
/** Attach a node to the manipulator.
Automatically detaches previously attached node.
setNode(NULL) detaches previously nodes.
Is ignored by manipulators which do not require a reference model.*/
virtual void setNode(osg::Node*);
/** Return node if attached.*/
virtual 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);
/** Start/restart the manipulator.*/
virtual void init(GUIEventAdapter& ea,GUIActionAdapter& us);
/** handle events, return true if handled, false otherwise.*/
virtual bool update(GUIEventAdapter& ea,GUIActionAdapter& us);
private:
/** Reset the internal GUIEvent stack.*/
void flushMouseEventStack();
/** Add the current mouse GUIEvent to internal stack.*/
void addMouseEvent(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();
void trackball(osg::Vec3& axis,float& angle, float p1x, float p1y, float p2x, float p2y);
float tb_project_to_sphere(float r, float x, float y);
/** Check the speed at which the mouse is moving.
If speed is below a threshold then return false, otherwise return true.*/
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<osg::Node> _node;
float _modelScale;
float _minimumZoomScale;
bool _thrown;
};
}
#endif

35
include/osgUtil/Version Normal file
View File

@@ -0,0 +1,35 @@
#ifndef OSGUTIL_VERSION
#define OSGUTIL_VERSION 1
#include <osgUtil/Export>
extern "C" {
/**
* getVersion_osgUtil() returns the library version number.
* Numbering conventon : osg_src-0.8-31 will return 0.8.31 from getVersion_osgUtil.
*
* 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) utility library
#
AC_CHECK_LIB(osg, osgUtilGetVersion, ,
[AC_MSG_ERROR(OpenSceneGraph utility library not found. See http://www.openscenegraph.org)],)
\endverbatim
*/
extern OSGUTIL_EXPORT const char* osgUtilGetVersion();
/**
* getLibraryName_osgUtil() returns the library name in human friendly form.
*/
extern OSGUTIL_EXPORT const char* osgUtilGetLibraryName();
};
#endif