*** empty log message ***

This commit is contained in:
Don BURNS 2003-06-24 15:40:09 +00:00
parent 5a939f5420
commit 15f88f35b2
91 changed files with 2871 additions and 1937 deletions

View File

@ -35,9 +35,9 @@ MAKEDEPEND = ignore
##
## Usage:
## Default - VERSION_REVISION is set to the value defined here
## Env variable PRODUCER_VERSION_REVISION overrides default
## Env variable OSG_VERSION_REVISION overrides default
## e.g.:
## % setenv PRODUCER_VERSION_REVISION 5
## % setenv OSG_VERSION_REVISION 5
## % make version
## Command line overrides env variable
## % make VERSION_REVISION=
@ -386,16 +386,17 @@ ifeq ($(OS),CYGWIN)
LIB_EXT = dll
PLUGIN_EXT = dll
LINK = cp -f
INST_SYS_PREFIX = /usr/local/OpenSceneGraph
INST_LIBS = $(INST_SYS_PREFIX)/bin
INST_PLUGINS = $(INST_SYS_PREFIX)/bin
INST_INCLUDE = $(INST_SYS_PREFIX)/include
INST_LOCATION = /usr/local/OpenSceneGraph
INST_LIBS = $(INST_LOCATION)/bin
INST_PLUGINS = $(INST_LOCATION)/bin
INST_INCLUDE = $(INST_LOCATION)/include
INST_SHARE_PREFIX = /usr/local/OpenSceneGraph
INST_SRC = $(INST_SHARE_PREFIX)/src
INST_EXAMPLES = $(INST_SHARE_PREFIX)/bin
INST_EXAMPLE_SRC = $(INST_SHARE_PREFIX)/src/demos
INST_DOC = $(INST_SHARE_PREFIX)/doc
INST_DATA = $(INST_SHARE_PREFIX)/data
MAKEDIST = $(TOPDIR)/Make/makeinnosetup
endif
#### Cygwin/Mingw specific definitions
@ -432,10 +433,10 @@ ifeq ($(OS),MINGW)
LIB_EXT = dll
PLUGIN_EXT = dll
LINK = cp -f
INST_SYS_PREFIX = /usr/local/OpenSceneGraph
INST_LIBS = $(INST_SYS_PREFIX)/bin
INST_PLUGINS = $(INST_SYS_PREFIX)/bin
INST_INCLUDE = $(INST_SYS_PREFIX)/include
INST_LOCATION = /usr/local/OpenSceneGraph
INST_LIBS = $(INST_LOCATION)/bin
INST_PLUGINS = $(INST_LOCATION)/bin
INST_INCLUDE = $(INST_LOCATION)/include
INST_SHARE_PREFIX = /usr/local/OpenSceneGraph
INST_SRC = $(INST_SHARE_PREFIX)/src
INST_EXAMPLES = $(INST_SHARE_PREFIX)/bin

View File

@ -128,6 +128,7 @@ EXAMPLE_DIRS = \
osgparticle\
osgpick\
osgprerender\
osgpoints\
osgreflect\
osgscribe\
osgsequence\
@ -146,8 +147,10 @@ EXAMPLE_DIRS = \
osgversion\
osgvertexprogram\
osgviewer\
osgprerendercubemap\
# osgprerendercubemap\
# osgsimulation\
# osgdemeter\
# osgjigsaw\
# comment in you want to compile the cluster demo.

View File

@ -23,7 +23,7 @@ print_pkginfo()
PKG="$1"
NAME="$2"
`[ "$OS" = "SunOS" ] && echo ARCH=sparc`
VERSION=`$TOPDIR/bin/osgversion`
VERSION=`gmake -s version`
CATEGORY="application,graphics,opengl"
DESC="$3"
BASEDIR="/opt/"
@ -67,7 +67,7 @@ make_installable()
{
PKGNAME=$1
PKGDIR=$PKGNAME.pkg
DISTNAME="$PKGNAME"-"`$TOPDIR/bin/osgversion`"-"$OS".shar
DISTNAME="$PKGNAME"-"`gmake -s version`"-"$OS".shar
THISDIR=`pwd`
cd $PKGSUBDIR

View File

@ -753,6 +753,33 @@ Package=<4>
###############################################################################
Project: "Example osgprerendercubemap"=.\examples\osgprerendercubemap\osgprerendercubemap.dsp - Package Owner=<4>
Package=<5>
{{{
}}}
Package=<4>
{{{
Begin Project Dependency
Project_Dep_Name Core osg
End Project Dependency
Begin Project Dependency
Project_Dep_Name Core osgDB
End Project Dependency
Begin Project Dependency
Project_Dep_Name Core osgGA
End Project Dependency
Begin Project Dependency
Project_Dep_Name Core osgProducer
End Project Dependency
Begin Project Dependency
Project_Dep_Name Core osgUtil
End Project Dependency
}}}
###############################################################################
Project: "Example osgreflect"=.\examples\osgreflect\osgreflect.dsp - Package Owner=<4>
Package=<5>

View File

@ -421,6 +421,10 @@ SOURCE=..\..\src\osg\Transform.cpp
# End Source File
# Begin Source File
SOURCE=..\..\src\osg\TransformAttributeFunctor.cpp
# End Source File
# Begin Source File
SOURCE=..\..\src\osg\BlendFunc.cpp
# End Source File
# Begin Source File
@ -837,6 +841,11 @@ SOURCE=..\..\Include\Osg\Transform
# End Source File
# Begin Source File
SOURCE=..\..\Include\Osg\TransformAttributeFunctor
# End Source File
# Begin Source File
SOURCE=..\..\Include\Osg\TriangleFunctor
# End Source File
# Begin Source File

View File

@ -15,5 +15,13 @@ EXEC = osgcameragroup
INC += $(PRODUCER_INCLUDE_DIR) -I/usr/X11R6/include -I/usr/X11R6/include
LDFLAGS += $(PRODUCER_LIB_DIR) -L/usr/X11R6/lib
ifeq ($(USE_OPEN_THREAD),1)
DEF += -D_USE_OPEN_THREAD
INC += $(INC_OPEN_THREAD)
LDFLAGS += $(LIB_OPEN_THREAD)
LIBS += -lOpenThread
endif
include $(TOPDIR)/Make/makerules

View File

@ -149,10 +149,10 @@ int main( int argc, char **argv )
const osg::BoundingSphere& bs = loadedModel->getBound();
Producer::Trackball tb;
tb.setOrientation( Producer::Trackball::Z_UP );
tb.setDistance(bs.radius()*3.0f);
tb.translate(-bs.center().x(),-bs.center().y(),-bs.center().z());
osg::ref_ptr<Producer::Trackball> tb = new Producer::Trackball;
tb->setOrientation( Producer::Trackball::Z_UP );
tb->setDistance(bs.radius()*3.0f);
tb->translate(-bs.center().x(),-bs.center().y(),-bs.center().z());
// create the windows and run the threads.
cg.realize();
@ -168,10 +168,10 @@ int main( int argc, char **argv )
// call all node update callbacks and animations.
cg.getSceneData()->accept(update);
tb.input( kbmcb.mx(), kbmcb.my(), kbmcb.mbutton() );
tb->input( kbmcb.mx(), kbmcb.my(), kbmcb.mbutton() );
// update the main producer camera
cg.setViewByMatrix(tb.getMatrix());
cg.setViewByMatrix(tb->getMatrix());
// fire off the cull and draw traversals of the scene.
cg.frame();

View File

@ -9,6 +9,8 @@
#include <osgDB/WriteFile>
#include <osgDB/ReaderWriter>
#include <osgUtil/Optimizer>
#include "OrientationConverter.h"
#include "GeoSet.h"
@ -273,6 +275,10 @@ int main( int argc, char **argv )
ConvertGeoSetsToGeometryVisitor cgtg;
root->accept(cgtg);
// optimize the scene graph, remove rendundent nodes and state etc.
osgUtil::Optimizer optimizer;
optimizer.optimize(root.get());
if( do_convert )
root = oc.convert( root.get() );

View File

@ -35,8 +35,17 @@ osg::Node* createHUD()
// turn lighting off for the text and disable depth test to ensure its always ontop.
osg::StateSet* stateset = geode->getOrCreateStateSet();
stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
//stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
#if 0
// to ensure the hud appears on top we can either use osg::Depth to force the
// depth fragments to be placed at the front of the screen.
stateset->setAttribute(new osg::Depth(osg::Depth::LESS,0.0,0.0001));
#else
// or disable depth test, and make sure that the hud is drawn after everything
// else so that it always appears ontop.
stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
stateset->setRenderBinDetails(11,"RenderBin");
#endif
osg::Vec3 position(150.0f,800.0f,0.0f);
osg::Vec3 delta(0.0f,-120.0f,0.0f);

View File

@ -356,7 +356,7 @@ int main( int argc, char **argv )
++itr)
{
// switch off small feature culling to prevent the light points from being culled.
osgUtil::SceneView* sceneview = itr->get();
osgUtil::SceneView* sceneview = (*itr)->getSceneView();
sceneview->setCullingMode( sceneview->getCullingMode() & ~osg::CullStack::SMALL_FEATURE_CULLING);
}

View File

@ -508,7 +508,7 @@ int main( int argc, char **argv )
itr!=viewer.getSceneHandlerList().end();
++itr)
{
osgUtil::SceneView* sceneview = itr->get();
osgUtil::SceneView* sceneview = (*itr)->getSceneView();
sceneview->setCullMask(0xffffffff);
sceneview->setCullMaskLeft(0x00000001);
sceneview->setCullMaskRight(0x00000002);

View File

@ -20,9 +20,9 @@
#include <osg/Geometry>
#include <osg/Geode>
#include <osg/Group>
#include <osg/Projection>
#include <osg/MatrixTransform>
#include <osgText/Text>
#include <osgDB/Registry>
@ -137,18 +137,14 @@ osg::Node* createRectangle(osg::BoundingBox& bb,
// disable display list so our modified tex coordinates show up
geom->setUseDisplayList(false);
osg::Geode* geode = new osg::Geode;
geode->addDrawable(geom);
// setup texture
osg::TextureRectangle* texture = new osg::TextureRectangle;
texture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP);
texture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP);
// load image
osg::Image* img = osgDB::readImageFile(filename);
texture->setImage(img);
// setup state
osg::StateSet* state = geom->getOrCreateStateSet();
state->setTextureAttributeAndModes(0, texture, osg::StateAttribute::ON);
@ -156,6 +152,8 @@ osg::Node* createRectangle(osg::BoundingBox& bb,
state->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
// install 'update' callback
osg::Geode* geode = new osg::Geode;
geode->addDrawable(geom);
geode->setUpdateCallback(new TexturePanCallback(geom, img));
return geode;
@ -190,17 +188,17 @@ osg::Node* createHUD()
state->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
// add text
osg::Vec3 pos(150.0f, 800.0f, 0.0f);
osg::Vec3 pos(120.0f, 800.0f, 0.0f);
const osg::Vec3 delta(0.0f, -80.0f, 0.0f);
const char* text[] = {
"TextureRectangle Mini-HOWTO",
"- essentially behaves like Texture2D, *except* that:",
"- tex coords must be non-normalized (0..width) instead of (0..1)",
"- wrap mode must be CLAMP, CLAMP_TO_EDGE, or CLAMP_TO_BORDER",
"- repeating wrap modes are *not* supported",
"- texture border is *not* supported",
"- texture mipmaps are *not* supported",
"- tex coords must be non-normalized (0..pixel) instead of (0..1)",
"- wrap modes must be CLAMP, CLAMP_TO_EDGE, or CLAMP_TO_BORDER\n repeating wrap modes are not supported",
"- filter modes must be NEAREST or LINEAR since\n mipmaps are not supported",
"- texture borders are not supported",
"- defaults should be fine",
NULL
};
const char** t = text;
@ -226,9 +224,11 @@ osg::Node* createHUD()
osg::Node* createModel(const std::string& filename)
{
osg::Group* root = new osg::Group;
osg::BoundingBox bb(0.0f,0.0f,0.0f,1.0f,1.0f,1.0f);
root->addChild(createRectangle(bb, filename)); // XXX
if (filename != "X") {
osg::BoundingBox bb(0.0f,0.0f,0.0f,1.0f,1.0f,1.0f);
root->addChild(createRectangle(bb, filename)); // XXX
}
root->addChild(createHUD());

View File

@ -13,6 +13,43 @@
#include <osgUtil/Optimizer>
#include <osgProducer/Viewer>
#if 0
enum Methods
{
SET_1,
SET_2,
END
};
typedef std::pair<Methods,std::string> MethodPair;
class Proxy
{
public:
Proxy(MethodPair* methods)
{
std::cout<<"methods "<<methods<<std::endl;
for(int i=0;methods[i].first!=END;++i)
{
std::cout<<"\t"<<methods[i].first<<"\t"<<methods[i].second<<std::endl;
}
}
};
static MethodPair methods[] =
{
MethodPair(SET_1,"SET_1"),
MethodPair(SET_2,"SET_2"),
MethodPair(END,"")
};
Proxy myproxy(methods);
#endif
int main( int argc, char **argv )
{

View File

@ -64,7 +64,7 @@ class SG_EXPORT CollectOccludersVisitor : public osg::NodeVisitor, public osg::C
protected:
/** prevent unwanted copy construction.*/
CollectOccludersVisitor(const CollectOccludersVisitor&):osg::NodeVisitor(),osg::CullStack() {}
//CollectOccludersVisitor(const CollectOccludersVisitor&):osg::NodeVisitor(),osg::CullStack() {}
/** prevent unwanted copy operator.*/
CollectOccludersVisitor& operator = (const CollectOccludersVisitor&) { return *this; }

View File

@ -340,7 +340,9 @@ class SG_EXPORT Drawable : public Object
virtual ~PrimitiveFunctor() {}
virtual void setVertexArray(unsigned int count,const Vec2* vertices) = 0;
virtual void setVertexArray(unsigned int count,const Vec3* vertices) = 0;
virtual void setVertexArray(unsigned int count,const Vec4* vertices) = 0;
virtual void drawArrays(GLenum mode,GLint first,GLsizei count) = 0;
virtual void drawElements(GLenum mode,GLsizei count,const GLubyte* indices) = 0;
@ -348,8 +350,12 @@ class SG_EXPORT Drawable : public Object
virtual void drawElements(GLenum mode,GLsizei count,const GLuint* indices) = 0;
virtual void begin(GLenum mode) = 0;
virtual void vertex(const Vec2& vert) = 0;
virtual void vertex(const Vec3& vert) = 0;
virtual void vertex(const Vec4& vert) = 0;
virtual void vertex(float x,float y) = 0;
virtual void vertex(float x,float y,float z) = 0;
virtual void vertex(float x,float y,float z,float w) = 0;
virtual void end() = 0;
};

View File

@ -51,9 +51,9 @@ class SG_EXPORT Geometry : public Drawable
BIND_PER_VERTEX
};
void setVertexArray(Vec3Array* array) { _vertexArray = array; dirtyDisplayList(); dirtyBound(); }
Vec3Array* getVertexArray() { return _vertexArray.get(); }
const Vec3Array* getVertexArray() const { return _vertexArray.get(); }
void setVertexArray(Array* array) { _vertexArray = array; dirtyDisplayList(); dirtyBound(); }
Array* getVertexArray() { return _vertexArray.get(); }
const Array* getVertexArray() const { return _vertexArray.get(); }
void setVertexIndices(IndexArray* array) { _vertexIndices = array; _fastPathComputed=false; dirtyDisplayList(); dirtyBound(); }
IndexArray* getVertexIndices() { return _vertexIndices.get(); }
@ -366,31 +366,31 @@ class SG_EXPORT Geometry : public Drawable
#ifdef COMPILE_POSSIBLE_NEW_ARRAY_METHODS
AttributeList _attributeList;
#endif
ref_ptr<Vec3Array> _vertexArray;
ref_ptr<IndexArray> _vertexIndices;
ref_ptr<Array> _vertexArray;
ref_ptr<IndexArray> _vertexIndices;
mutable AttributeBinding _normalBinding;
ref_ptr<Vec3Array> _normalArray;
ref_ptr<IndexArray> _normalIndices;
ref_ptr<Vec3Array> _normalArray;
ref_ptr<IndexArray> _normalIndices;
mutable AttributeBinding _colorBinding;
ref_ptr<Array> _colorArray;
ref_ptr<IndexArray> _colorIndices;
ref_ptr<Array> _colorArray;
ref_ptr<IndexArray> _colorIndices;
mutable AttributeBinding _secondaryColorBinding;
ref_ptr<Array> _secondaryColorArray;
ref_ptr<IndexArray> _secondaryColorIndices;
ref_ptr<Array> _secondaryColorArray;
ref_ptr<IndexArray> _secondaryColorIndices;
mutable AttributeBinding _fogCoordBinding;
ref_ptr<Array> _fogCoordArray;
ref_ptr<IndexArray> _fogCoordIndices;
ref_ptr<Array> _fogCoordArray;
ref_ptr<IndexArray> _fogCoordIndices;
TexCoordArrayList _texCoordList;
TexCoordArrayList _texCoordList;
VertexAttribArrayList _vertexAttribList;
mutable VertexAttribBindingList _vertexAttribBindingList;
VertexAttribArrayList _vertexAttribList;
mutable VertexAttribBindingList _vertexAttribBindingList;
mutable bool _fastPathComputed;
mutable bool _fastPathComputed;
mutable bool _fastPath;
};

View File

@ -155,6 +155,9 @@ class SG_EXPORT Image : public Object
/** return the numbers of bytes the whole row/image/volume of pixels occupies.*/
inline unsigned int getTotalSizeInBytes() const { return getImageSizeInBytes()*_r; }
/** return the numbers of bytes the whole row/image/volume of pixels occupies, including all mip maps if included.*/
unsigned int getTotalSizeInBytesIncludingMipmaps() const;
/** raw image data.*/
inline unsigned char *data() { return _data; }

View File

@ -113,6 +113,12 @@ const double PI_4 = 0.78539816339744830962;
template<typename T>
inline T absolute(T v) { return v<(T)0?-v:v; }
/** return true if float lhs and rhs are equivalent, meaning that the difference between then is less than an epsilon value which default to 1e-6.*/
inline float equivalent(float lhs,float rhs,float epsilon=1e-6) { float delta = rhs-lhs; return delta<0.0f?delta>=-epsilon:delta<=epsilon; }
/** return true if double lhs and rhs are equivalent, meaning that the difference between then is less than an epsilon value which default to 1e-6.*/
inline double equivalent(double lhs,double rhs,double epsilon=1e-6) { double delta = rhs-lhs; return delta<0.0?delta>=-epsilon:delta<=epsilon; }
/** return the minimum of two values, equivilant to std::min.
* std::min not used because of STL implementation under IRIX contains no std::min.*/
template<typename T>

View File

@ -31,7 +31,9 @@ class SG_EXPORT Point : public StateAttribute
StateAttribute(point,copyop),
_size(point._size),
_fadeThresholdSize(point._fadeThresholdSize),
_distanceAttenuation(point._distanceAttenuation) {}
_distanceAttenuation(point._distanceAttenuation),
_minSize(point._minSize),
_maxSize(point._maxSize) {}
META_StateAttribute(osg, Point, POINT);
@ -46,6 +48,8 @@ class SG_EXPORT Point : public StateAttribute
COMPARE_StateAttribute_Parameter(_size)
COMPARE_StateAttribute_Parameter(_fadeThresholdSize)
COMPARE_StateAttribute_Parameter(_distanceAttenuation)
COMPARE_StateAttribute_Parameter(_minSize)
COMPARE_StateAttribute_Parameter(_maxSize)
return 0; // passed all the above comparison macro's, must be equal.
}
@ -64,6 +68,12 @@ class SG_EXPORT Point : public StateAttribute
void setDistanceAttenuation(const Vec3& distanceAttenuation);
inline const Vec3& getDistanceAttenuation() const { return _distanceAttenuation; }
void setMinSize(float minSize);
inline float getMinSize() const {return _minSize;}
void setMaxSize(float maxSize);
inline float getMaxSize() const {return _maxSize;}
virtual void apply(State& state) const;
static void init_GL_EXT();
@ -75,6 +85,8 @@ class SG_EXPORT Point : public StateAttribute
float _size;
float _fadeThresholdSize;
Vec3 _distanceAttenuation;
float _minSize;
float _maxSize;
};

View File

@ -21,6 +21,7 @@
#include <osg/FrameStamp>
#include <osg/DisplaySettings>
#include <osg/Polytope>
#include <osg/Viewport>
#include <vector>
#include <map>
@ -79,6 +80,12 @@ class SG_EXPORT State : public Referenced
/** reset the state object to an empty stack.*/
void reset();
inline const Viewport* getCurrentViewport() const
{
return static_cast<const Viewport*>(getLastAppliedAttribute(osg::StateAttribute::VIEWPORT));
}
inline void applyProjectionMatrix(const osg::RefMatrix* matrix)
{

View File

@ -84,8 +84,8 @@ class SG_EXPORT TextureRectangle : public Texture
SubloadCallback* getSubloadCallback() { return _subloadCallback.get(); }
const SubloadCallback* getSubloadCallback() const { return _subloadCallback.get(); }
/** On first apply (unless already compiled), create the minmapped
* texture and bind it, subsequent apply will simple bind to texture.*/
/** On first apply (unless already compiled), create and bind the
* texture, subsequent apply will simple bind to texture.*/
virtual void apply(State& state) const;
protected :
@ -94,7 +94,9 @@ class SG_EXPORT TextureRectangle : public Texture
virtual void computeInternalFormat() const;
void applyTexImageRectangle(GLenum target, Image* image, State& state, GLsizei& inwidth, GLsizei& inheight) const;
void applyTexParameters(GLenum target, State& state) const;
void applyTexImage(GLenum target, Image* image, State& state, GLsizei& inwidth, GLsizei& inheight) const;
// not ideal that _image is mutable, but its required since
// Image::ensureDimensionsArePowerOfTwo() can only be called

View File

@ -15,6 +15,7 @@
#define OSG_TRIANGLEFUNCTOR 1
#include <osg/Drawable>
#include <osg/Notify>
namespace osg {
@ -32,12 +33,23 @@ public:
virtual ~TriangleFunctor() {}
virtual void setVertexArray(unsigned int count,const Vec2* vertices)
{
notify(WARN)<<"Triangle Functor does not support Vec2* vertex arrays"<<std::endl;
}
virtual void setVertexArray(unsigned int count,const Vec3* vertices)
{
_vertexArraySize = count;
_vertexArrayPtr = vertices;
}
virtual void setVertexArray(unsigned int count,const Vec4* vertices)
{
notify(WARN)<<"Triangle Functor does not support Vec4* vertex arrays"<<std::endl;
}
virtual void drawArrays(GLenum mode,GLint first,GLsizei count)
{
if (_vertexArrayPtr==0 && count==0) return;
@ -311,15 +323,19 @@ public:
* non vertex array primitives to vertex array based primitives.
* this is done to simplify the implementation of primtive functor
* subclasses - users only need override drawArray and drawElements.*/
inline void begin(GLenum mode)
virtual void begin(GLenum mode)
{
_modeCache = mode;
_vertexCache.clear();
}
inline void vertex(const Vec3& vert) { _vertexCache.push_back(vert); }
inline void vertex(float x,float y,float z) { _vertexCache.push_back(osg::Vec3(x,y,z)); }
inline void end()
virtual void vertex(const Vec2& vert) { _vertexCache.push_back(osg::Vec3(vert[0],vert[1],0.0f)); }
virtual void vertex(const Vec3& vert) { _vertexCache.push_back(vert); }
virtual void vertex(const Vec4& vert) { _vertexCache.push_back(osg::Vec3(vert[0],vert[1],vert[2])/vert[3]); }
virtual void vertex(float x,float y) { _vertexCache.push_back(osg::Vec3(x,y,0.0f)); }
virtual void vertex(float x,float y,float z) { _vertexCache.push_back(osg::Vec3(x,y,z)); }
virtual void vertex(float x,float y,float z,float w) { _vertexCache.push_back(osg::Vec3(x,y,z)/w); }
virtual void end()
{
if (!_vertexCache.empty())
{

View File

@ -106,11 +106,11 @@ public:
virtual bool removeChild(GUIEventHandler *geh);
const int getNumChildren() const { return _children.size(); }
unsigned int getNumChildren() const { return _children.size(); }
GUIEventHandler *getChild( int i) { return _children[i].get(); }
GUIEventHandler *getChild( unsigned int i) { return _children[i].get(); }
const GUIEventHandler *getChild( int i ) const { return _children[i].get(); }
const GUIEventHandler *getChild( unsigned int i ) const { return _children[i].get(); }
bool containsNode( const GUIEventHandler* node ) const
{

View File

@ -52,7 +52,7 @@ class OSGPRODUCER_EXPORT OsgCameraGroup : public Producer::CameraGroup
const osg::ApplicationUsage* getApplicationUsage() const { return _applicationUsage; }
typedef std::vector < osg::ref_ptr<osgProducer::OsgSceneHandler> > SceneHandlerList;
typedef std::vector < Producer::ref_ptr<osgProducer::OsgSceneHandler> > SceneHandlerList;
SceneHandlerList& getSceneHandlerList() { return _shvec;}

View File

@ -22,11 +22,20 @@
namespace osgProducer {
class OSGPRODUCER_EXPORT OsgSceneHandler : public Producer::Camera::SceneHandler, public osgUtil::SceneView
class OSGPRODUCER_EXPORT OsgSceneHandler : public Producer::Camera::SceneHandler
{
public :
OsgSceneHandler(osg::DisplaySettings *ds = NULL);
/// set the scene view to which will manage rendering of the OSG scene.
void setSceneView(osgUtil::SceneView* sceneView) { _sceneView = sceneView; }
/// get the scene view.
osgUtil::SceneView* getSceneView() { return _sceneView.get(); }
/// get the const scene view.
const osgUtil::SceneView* getSceneView() const { return _sceneView.get(); }
/// override the init method to force it be run one at a time.
virtual void init();
@ -84,6 +93,9 @@ class OSGPRODUCER_EXPORT OsgSceneHandler : public Producer::Camera::SceneHandler
protected:
virtual ~OsgSceneHandler() {}
osg::ref_ptr<osgUtil::SceneView> _sceneView;
osg::ref_ptr<Callback> _clearCallback;
osg::ref_ptr<Callback> _cullCallback;

View File

@ -82,7 +82,18 @@ class OSGPRODUCER_EXPORT Viewer : public OsgCameraGroup, public osgGA::GUIAction
virtual bool realize();
/** Updated the scene. Handle any queued up events, do an update traversal and set the CameraGroup's setViewByMatrix if any camera manipulators are active.*/
virtual void update();
/** set the update visitor which does the update traversal of the scene graph. Automatically called by the update() method.*/
void setUpdateVistor(osg::NodeVisitor* nv) { _updateVisitor = nv; }
/** get the update visitor.*/
osg::NodeVisitor* getUpdateVistor() { return _updateVisitor.get(); }
/** get the const update visitor.*/
const osg::NodeVisitor* getUpdateVistor() const { return _updateVisitor.get(); }
/** Dispatch the cull and draw for each of the Camera's for this frame.*/
virtual void frame();

View File

@ -45,6 +45,9 @@ class OSGSIM_EXPORT LightPointNode : public osg::Node
virtual void traverse(osg::NodeVisitor& nv);
unsigned int getNumLightPoints() const { return _lightPointList.size(); }
unsigned int addLightPoint(const LightPoint& lp);
void removeLightPoint(unsigned int pos);

View File

@ -100,6 +100,18 @@ public:
float getCharacterHeight() const { return _characterHeight; }
float getCharacterAspectRatio() const { return _characterAspectRatio; }
enum CharacterSizeMode
{
OBJECT_COORDS, /// default
SCREEN_COORDS, /// internally scale the characters to be constant screen size.
OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT /// text that behavaves like OBJECT_COORDS sized text when a long distance way, but has its screen sized capped automatically when the viewer gets near.
};
/** Set how the CharacterSize value relates to the final rendered character.*/
void setCharacterSizeMode(CharacterSizeMode mode) { _characterSizeMode = mode; }
/** Get the CharacterSizeMode.*/
CharacterSizeMode getCharacterSizeMode() const { return _characterSizeMode; }
/** Set the maximum width of the text box.
@ -165,27 +177,11 @@ public:
void setAxisAlignment(AxisAlignment axis);
void setRotation(const osg::Quat& quat);
void setRotation(unsigned int contextID, const osg::Quat& quat);
const osg::Quat& getRotation(unsigned int contextID=0) const { return _rotation[contextID]; }
const osg::Quat& getRotation() const { return _rotation; }
void setScale(float scale);
void setScale(unsigned int contextID, float scale);
float getScale(unsigned int contextID=0) const { return _scale[contextID]; }
void setScaleAndRotation(unsigned int contextID, float scale,const osg::Quat& quat);
void setAutoUpdateEyeMovementTolerance(float tolerance) { _autoUpdateEyeMovementTolerance = tolerance; }
float getAutoUpdateEyeMovementTolerance() const { return _autoUpdateEyeMovementTolerance; }
void setAutoRotateToScreen(bool autoRotateToScreen);
bool getAutoRotateToScreen() const { return _autoRotateToScreen; }
void setAutoScaleToLimitScreenSizeToFontResolution(bool autoScaleToScreen);
bool getAutoScaleToLimitScreenSizeToFontResolution() const { return _autoScaleToLimitScreenSizeToFontResolution; }
enum Layout
{
LEFT_TO_RIGHT, /// default
@ -295,35 +291,49 @@ protected:
unsigned int _fontHeight;
float _characterHeight;
float _characterAspectRatio;
CharacterSizeMode _characterSizeMode;
float _maximumWidth;
float _maximumHeight;
String _text;
osg::Vec3 _position;
AlignmentType _alignment;
mutable osg::buffered_object<osg::Quat> _rotation;
mutable osg::buffered_value<float> _scale;
float _autoUpdateEyeMovementTolerance;
osg::Quat _rotation;
bool _autoRotateToScreen;
bool _autoScaleToLimitScreenSizeToFontResolution;
Layout _layout;
osg::Vec4 _color;
unsigned int _drawMode;
// iternal map used for rendering. Set up by the computeGlyphRepresentation() method.
TextureGlyphQuadMap _textureGlyphQuadMap;
mutable TextureGlyphQuadMap _textureGlyphQuadMap;
void computeGlyphRepresentation();
// internal caches of the positioning of the text.
mutable osg::buffered_object<osg::Matrix> _matrix;
osg::Vec3 _offset;
osg::Vec3 _normal;
mutable osg::BoundingBox _textBB;
struct AutoTransformCache
{
AutoTransformCache():
_traversalNumber(-1),
_width(0),
_height(0) {}
int _traversalNumber;
int _width;
int _height;
osg::Vec3 _transformedPosition;
osg::Matrix _modelview;
osg::Matrix _projection;
osg::Matrix _matrix;
};
mutable osg::buffered_object<AutoTransformCache> _autoTransformCache;
mutable osg::Vec3 _offset;
mutable osg::Vec3 _normal;
mutable osg::BoundingBox _textBB;
void setUpAutoCallback();
void computePositions();
void computePositions(unsigned int contextID);
void computePositions(unsigned int contextID) const;
};

View File

@ -217,8 +217,8 @@ class OSGUTIL_EXPORT CullVisitor : public osg::NodeVisitor, public osg::CullStac
protected:
/** prevent unwanted copy construction.*/
CullVisitor(const CullVisitor&):osg::NodeVisitor(),osg::CullStack() {}
// /** prevent unwanted copy construction.*/
// CullVisitor(const CullVisitor&): osg::NodeVisitor(), osg::CullStack() {}
/** prevent unwanted copy operator.*/
CullVisitor& operator = (const CullVisitor&) { return *this; }

View File

@ -163,13 +163,13 @@ class OSGUTIL_EXPORT SceneView : public osg::Referenced
void setCullMask(const osg::Node::NodeMask nm) { _cullMask = nm; }
const osg::Node::NodeMask getCullMask() const { return _cullMask; }
osg::Node::NodeMask getCullMask() const { return _cullMask; }
void setCullMaskLeft(const osg::Node::NodeMask nm) { _cullMaskLeft = nm; }
const osg::Node::NodeMask getCullMaskLeft() const { return _cullMaskLeft; }
osg::Node::NodeMask getCullMaskLeft() const { return _cullMaskLeft; }
void setCullMaskRight(const osg::Node::NodeMask nm) { _cullMaskRight = nm; }
const osg::Node::NodeMask getCullMaskRight() const { return _cullMaskRight; }
osg::Node::NodeMask getCullMaskRight() const { return _cullMaskRight; }
/** Set the LOD bias for the CullVisitor to use.*/
void setLODScale(float bias) { _LODScale = bias; }

View File

@ -62,8 +62,8 @@ class OSGUTIL_EXPORT UpdateVisitor : public osg::NodeVisitor
protected:
/** prevent unwanted copy construction.*/
UpdateVisitor(const UpdateVisitor&):osg::NodeVisitor() {}
// /** prevent unwanted copy construction.*/
// UpdateVisitor(const UpdateVisitor&):osg::NodeVisitor() {}
/** prevent unwanted copy operator.*/
UpdateVisitor& operator = (const UpdateVisitor&) { return *this; }

View File

@ -11,6 +11,7 @@
* OpenSceneGraph Public License for more details.
*/
#include <osg/CullStack>
#include <osg/Timer>
using namespace osg;
@ -199,27 +200,79 @@ void CullStack::pushModelViewMatrix(RefMatrix* matrix)
_modelviewStack.push_back(matrix);
pushCullingSet();
//osg::Timer timer;
//osg::Timer_t tick_1 = timer.tick();
// fast method for computing the eye point in local coords which doesn't require the inverse matrix.
const float x_0 = (*matrix)(0,0);
const float x_1 = (*matrix)(1,0);
const float x_2 = (*matrix)(2,0);
const float x_scale = (*matrix)(3,0) / -(x_0*x_0+x_1*x_1+x_2*x_2);
const float x_len2 = (x_0*x_0+x_1*x_1+x_2*x_2);
const float y_0 = (*matrix)(0,1);
const float y_1 = (*matrix)(1,1);
const float y_2 = (*matrix)(2,1);
const float y_scale = (*matrix)(3,1) / -(y_0*y_0+y_1*y_1+y_2*y_2);
const float y_len2 = (y_0*y_0+y_1*y_1+y_2*y_2);
const float z_0 = (*matrix)(0,2);
const float z_1 = (*matrix)(1,2);
const float z_2 = (*matrix)(2,2);
const float z_scale = (*matrix)(3,2) / -(z_0*z_0+z_1*z_1+z_2*z_2);
const float z_len2 = (z_0*z_0+z_1*z_1+z_2*z_2);
bool useFastPath = (osg::equivalent(x_len2,y_len2) &&
osg::equivalent(x_len2,z_len2) &&
osg::equivalent(y_len2,z_len2));
// std::cout<<"x_len2 = "<<x_len2 << "\ty_len2 = "<<y_len2 << "\tz_len2 = "<<z_len2 << std::endl;
if (useFastPath)
{
const float xyz_len0 = x_0*x_0 + y_0*y_0 + z_0*z_0;
const float xyz_len1 = x_1*x_1 + y_1*y_1 + z_1*z_1;
const float xyz_len2 = x_2*x_2 + y_2*y_2 + z_2*z_2;
// std::cout<<"xyz_len0 = "<<xyz_len0 << "\txyz_len2 = "<<xyz_len1 << "\txyz_len2 = "<<xyz_len2 << std::endl;
if (!osg::equivalent(xyz_len0,xyz_len1) ||
!osg::equivalent(xyz_len0,xyz_len2) ||
!osg::equivalent(xyz_len1,xyz_len2)) useFastPath = false;
}
if (useFastPath)
{
// compute the eye point in local coords using a fast technique
// which assumes that only proportional scaling, no shearing, this
// is satisfied for most scene graph usage.
const float x_scale = (*matrix)(3,0) / -x_len2;
const float y_scale = (*matrix)(3,1) / -y_len2;
const float z_scale = (*matrix)(3,2) / -z_len2;
osg::Vec3 fast_eyepoint(x_0*x_scale + y_0*y_scale + z_0*z_scale,
x_1*x_scale + y_1*y_scale + z_1*z_scale,
x_2*x_scale + y_2*y_scale + z_2*z_scale);
_eyePointStack.push_back(fast_eyepoint);
// std::cout<<"fast path "<<*matrix<<std::endl;
}
else
{
// shearing or no proportional scaling has been detected so we
// callback to compute the inverse of the model view matrix and
// transforming the eye point into local coords. This is ten
// to thirty times slower than the above fast path.
osg::Vec3 slow_eyepoint(osg::Matrix::inverse(*matrix).getTrans());
_eyePointStack.push_back(slow_eyepoint);
//std::cout<<"slow path "<<*matrix<<std::endl;
}
_eyePointStack.push_back(osg::Vec3(x_0*x_scale + y_0*y_scale + z_0*z_scale,
x_1*x_scale + y_1*y_scale + z_1*z_scale,
x_2*x_scale + y_2*y_scale + z_2*z_scale));
osg::Vec3 lookVector = getLookVectorLocal();

View File

@ -257,8 +257,18 @@ struct ComputeBound : public Drawable::PrimitiveFunctor
{
ComputeBound():_vertices(0) {}
virtual void setVertexArray(unsigned int count,const Vec2* vertices)
{
notify(WARN)<<"ComputeBound does not support Vec2* vertex arrays"<<std::endl;
}
virtual void setVertexArray(unsigned int,const Vec3* vertices) { _vertices = vertices; }
virtual void setVertexArray(unsigned int count,const Vec4* vertices)
{
notify(WARN)<<"ComputeBound does not support Vec4* vertex arrays"<<std::endl;
}
virtual void drawArrays(GLenum,GLint first,GLsizei count)
{
if (_vertices)
@ -305,8 +315,12 @@ struct ComputeBound : public Drawable::PrimitiveFunctor
}
virtual void begin(GLenum) {}
virtual void vertex(const Vec2& vert) { _bb.expandBy(osg::Vec3(vert[0],vert[1],0.0f)); }
virtual void vertex(const Vec3& vert) { _bb.expandBy(vert); }
virtual void vertex(const Vec4& vert) { if (vert[3]!=0.0f) _bb.expandBy(osg::Vec3(vert[0],vert[1],vert[2])/vert[3]); }
virtual void vertex(float x,float y) { _bb.expandBy(x,y,1.0f); }
virtual void vertex(float x,float y,float z) { _bb.expandBy(x,y,z); }
virtual void vertex(float x,float y,float z,float w) { if (w!=0.0f) _bb.expandBy(x/w,y/w,z/w); }
virtual void end() {}
const Vec3* _vertices;

View File

@ -83,6 +83,7 @@ CXXFILES =\
Texture3D.cpp\
TextureCubeMap.cpp\
TextureRectangle.cpp\
TransformAttributeFunctor.cpp\
Timer.cpp\
Transform.cpp\
UnitTestFramework.cpp\

View File

@ -16,22 +16,26 @@
using namespace osg;
class DrawVertex
class DrawVertex : public osg::ConstValueVisitor
{
public:
DrawVertex(const Vec3Array* vertices,const IndexArray* indices):
DrawVertex(const Array* vertices,const IndexArray* indices):
_vertices(vertices),
_indices(indices) {}
void operator () (unsigned int pos)
{
if (_indices) glVertex3fv((*_vertices)[_indices->index(pos)].ptr());
else glVertex3fv((*_vertices)[pos].ptr());
if (_indices) _vertices->accept(_indices->index(pos),*this);
else _vertices->accept(pos,*this);
}
const Vec3Array* _vertices;
const IndexArray* _indices;
virtual void apply(const Vec2& v) { glVertex2fv(v.ptr()); }
virtual void apply(const Vec3& v) { glVertex3fv(v.ptr()); }
virtual void apply(const Vec4& v) { glVertex4fv(v.ptr()); }
const Array* _vertices;
const IndexArray* _indices;
};
class DrawNormal
@ -813,7 +817,7 @@ void Geometry::drawImplementation(State& state) const
//
if( _vertexArray.valid() )
state.setVertexPointer(3,GL_FLOAT,0,_vertexArray->getDataPointer());
state.setVertexPointer(_vertexArray->getDataSize(),_vertexArray->getDataType(),0,_vertexArray->getDataPointer());
else
state.disableVertexPointer();
@ -1547,13 +1551,26 @@ void Geometry::accept(ConstAttributeFunctor& af) const
void Geometry::accept(PrimitiveFunctor& functor) const
{
if (!_vertexArray.valid() || _vertexArray->empty()) return;
if (!_vertexArray.valid() || _vertexArray->getNumElements()==0) return;
if (!_vertexIndices.valid())
{
functor.setVertexArray(_vertexArray->size(),&(_vertexArray->front()));
switch(_vertexArray->getType())
{
case(Array::Vec2ArrayType):
functor.setVertexArray(_vertexArray->getNumElements(),static_cast<const Vec2*>(_vertexArray->getDataPointer()));
break;
case(Array::Vec3ArrayType):
functor.setVertexArray(_vertexArray->getNumElements(),static_cast<const Vec3*>(_vertexArray->getDataPointer()));
break;
case(Array::Vec4ArrayType):
functor.setVertexArray(_vertexArray->getNumElements(),static_cast<const Vec4*>(_vertexArray->getDataPointer()));
break;
default:
notify(WARN)<<"Warning: Geometry::accept(PrimtiveFunctor&) cannot handle Vertex Array type"<<_vertexArray->getType()<<std::endl;
return;
}
for(PrimitiveSetList::const_iterator itr=_primitives.begin();
itr!=_primitives.end();
++itr)
@ -1563,6 +1580,27 @@ void Geometry::accept(PrimitiveFunctor& functor) const
}
else
{
const Vec2Array* vec2Array = 0;
const Vec3Array* vec3Array = 0;
const Vec4Array* vec4Array = 0;
Array::Type type = _vertexArray->getType();
switch(type)
{
case(Array::Vec2ArrayType):
vec2Array = static_cast<const Vec2Array*>(_vertexArray.get());
break;
case(Array::Vec3ArrayType):
vec3Array = static_cast<const Vec3Array*>(_vertexArray.get());
break;
case(Array::Vec4ArrayType):
vec4Array = static_cast<const Vec4Array*>(_vertexArray.get());
break;
default:
notify(WARN)<<"Warning: Geometry::accept(PrimtiveFunctor&) cannot handle Vertex Array type"<<_vertexArray->getType()<<std::endl;
return;
}
for(PrimitiveSetList::const_iterator itr=_primitives.begin();
itr!=_primitives.end();
++itr)
@ -1581,7 +1619,21 @@ void Geometry::accept(PrimitiveFunctor& functor) const
vindex<indexEnd;
++vindex)
{
functor.vertex((*_vertexArray)[_vertexIndices->index(vindex)]);
switch(type)
{
case(Array::Vec2ArrayType):
functor.vertex((*vec2Array)[_vertexIndices->index(vindex)]);
break;
case(Array::Vec3ArrayType):
functor.vertex((*vec3Array)[_vertexIndices->index(vindex)]);
break;
case(Array::Vec4ArrayType):
functor.vertex((*vec4Array)[_vertexIndices->index(vindex)]);
break;
default:
break;
}
}
functor.end();
@ -1601,7 +1653,20 @@ void Geometry::accept(PrimitiveFunctor& functor) const
for(GLsizei primCount=0;primCount<*primItr;++primCount)
{
functor.vertex((*_vertexArray)[_vertexIndices->index(vindex)]);
switch(type)
{
case(Array::Vec2ArrayType):
functor.vertex((*vec2Array)[_vertexIndices->index(vindex)]);
break;
case(Array::Vec3ArrayType):
functor.vertex((*vec3Array)[_vertexIndices->index(vindex)]);
break;
case(Array::Vec4ArrayType):
functor.vertex((*vec4Array)[_vertexIndices->index(vindex)]);
break;
default:
break;
}
++vindex;
}
@ -1621,7 +1686,20 @@ void Geometry::accept(PrimitiveFunctor& functor) const
++primCount,++primItr)
{
unsigned int vindex=*primItr;
functor.vertex((*_vertexArray)[_vertexIndices->index(vindex)]);
switch(type)
{
case(Array::Vec2ArrayType):
functor.vertex((*vec2Array)[_vertexIndices->index(vindex)]);
break;
case(Array::Vec3ArrayType):
functor.vertex((*vec3Array)[_vertexIndices->index(vindex)]);
break;
case(Array::Vec4ArrayType):
functor.vertex((*vec4Array)[_vertexIndices->index(vindex)]);
break;
default:
break;
}
}
functor.end();
@ -1637,7 +1715,20 @@ void Geometry::accept(PrimitiveFunctor& functor) const
++primItr)
{
unsigned int vindex=*primItr;
functor.vertex((*_vertexArray)[_vertexIndices->index(vindex)]);
switch(type)
{
case(Array::Vec2ArrayType):
functor.vertex((*vec2Array)[_vertexIndices->index(vindex)]);
break;
case(Array::Vec3ArrayType):
functor.vertex((*vec3Array)[_vertexIndices->index(vindex)]);
break;
case(Array::Vec4ArrayType):
functor.vertex((*vec4Array)[_vertexIndices->index(vindex)]);
break;
default:
break;
}
}
functor.end();
@ -1653,7 +1744,20 @@ void Geometry::accept(PrimitiveFunctor& functor) const
++primItr)
{
unsigned int vindex=*primItr;
functor.vertex((*_vertexArray)[_vertexIndices->index(vindex)]);
switch(type)
{
case(Array::Vec2ArrayType):
functor.vertex((*vec2Array)[_vertexIndices->index(vindex)]);
break;
case(Array::Vec3ArrayType):
functor.vertex((*vec3Array)[_vertexIndices->index(vindex)]);
break;
case(Array::Vec4ArrayType):
functor.vertex((*vec4Array)[_vertexIndices->index(vindex)]);
break;
default:
break;
}
}
functor.end();
@ -1742,7 +1846,7 @@ void Geometry::computeCorrectBindingsAndArraySizes()
{
if (verifyBindings()) return;
if (!_vertexArray.valid() || _vertexArray->empty())
if (!_vertexArray.valid() || _vertexArray->getNumElements()==0)
{
// no vertex array so switch everything off.

View File

@ -142,6 +142,7 @@ unsigned int Image::computeNumComponents(GLenum format)
switch(format)
{
case(GL_COMPRESSED_RGB_S3TC_DXT1_EXT): return 3;
case(GL_COMPRESSED_RGBA_S3TC_DXT1_EXT): return 4;
case(GL_COMPRESSED_RGBA_S3TC_DXT3_EXT): return 4;
case(GL_COMPRESSED_RGBA_S3TC_DXT5_EXT): return 4;
case(GL_COLOR_INDEX): return 1;
@ -157,7 +158,11 @@ unsigned int Image::computeNumComponents(GLenum format)
case(GL_BGRA): return 4;
case(GL_LUMINANCE): return 1;
case(GL_LUMINANCE_ALPHA): return 2;
default: return 0;
default:
{
std::cout<<"error format = "<<std::hex<<format<<std::endl;
return 0;
}
}
}
@ -167,6 +172,8 @@ unsigned int Image::computePixelSizeInBits(GLenum format,GLenum type)
switch(type)
{
case(GL_COMPRESSED_RGB_S3TC_DXT1_EXT): return 4;
case(GL_COMPRESSED_RGBA_S3TC_DXT1_EXT): return 4;
case(GL_COMPRESSED_RGBA_S3TC_DXT3_EXT): return 8;
@ -199,7 +206,11 @@ unsigned int Image::computePixelSizeInBits(GLenum format,GLenum type)
case(GL_UNSIGNED_INT_8_8_8_8_REV):
case(GL_UNSIGNED_INT_10_10_10_2):
case(GL_UNSIGNED_INT_2_10_10_10_REV): return 32;
default: return 0;
default:
{
std::cout<<"error type = "<<type<<std::endl;
return 0;
}
}
}
@ -209,6 +220,7 @@ unsigned int Image::computeRowWidthInBytes(int width,GLenum format,GLenum type,i
unsigned int pixelSize = computePixelSizeInBits(format,type);
int widthInBits = width*pixelSize;
int packingInBits = packing*8;
std::cout << "width="<<width<<" pixelSize="<<pixelSize<<" width in bit="<<widthInBits<<" packingInBits="<<packingInBits<<" widthInBits%packingInBits="<<widthInBits%packingInBits<<std::endl;
return (widthInBits/packingInBits + ((widthInBits%packingInBits)?1:0))*packing;
}
@ -227,6 +239,40 @@ int Image::computeNearestPowerOfTwo(int s,float bias)
return s;
}
unsigned int Image::getTotalSizeInBytesIncludingMipmaps() const
{
if (_mipmapData.empty())
{
// no mips so just return size of main image
return getTotalSizeInBytes();
}
int s = _s;
int t = _t;
int r = _r;
unsigned int maxValue = 0;
for(unsigned int i=0;i<_mipmapData.size() && _mipmapData[i];++i)
{
s >>= 1;
t >>= 1;
r >>= 1;
maxValue = maximum(maxValue,_mipmapData[i]);
}
if (s==0) s=1;
if (t==0) t=1;
if (r==0) r=1;
unsigned int sizeOfLastMipMap = computeRowWidthInBytes(s,_pixelFormat,_dataType,_packing)*
r*t;
// std::cout<<"sizeOfLastMipMap="<<sizeOfLastMipMap<<"\ts="<<s<<"\tt="<<t<<"\tr"<<r<<std::endl;
return maxValue+sizeOfLastMipMap;
}
void Image::setInternalTextureFormat(GLint internalFormat)
{
// won't do any sanity checking right now, leave it to

View File

@ -53,17 +53,17 @@ void Material::setAmbient(Face face, const Vec4& ambient )
case(FRONT):
_ambientFrontAndBack = false;
_ambientFront = ambient;
clampArray4BetweenRange(_ambientFront,0.0f,1.0f,"osg::Material::setAmbient(..)");
//clampArray4BetweenRange(_ambientFront,0.0f,1.0f,"osg::Material::setAmbient(..)");
break;
case(BACK):
_ambientFrontAndBack = false;
_ambientBack = ambient;
clampArray4BetweenRange(_ambientBack,0.0f,1.0f,"Material::setAmbient(..)");
//clampArray4BetweenRange(_ambientBack,0.0f,1.0f,"Material::setAmbient(..)");
break;
case(FRONT_AND_BACK):
_ambientFrontAndBack = true;
_ambientFront = ambient;
clampArray4BetweenRange(_ambientFront,0.0f,1.0f,"Material::setAmbient(..)");
//clampArray4BetweenRange(_ambientFront,0.0f,1.0f,"Material::setAmbient(..)");
_ambientBack = _ambientFront;
break;
default:
@ -100,17 +100,17 @@ void Material::setDiffuse(Face face, const Vec4& diffuse )
case(FRONT):
_diffuseFrontAndBack = false;
_diffuseFront = diffuse;
clampArray4BetweenRange(_diffuseFront,0.0f,1.0f,"Material::setDiffuse(..)");
//clampArray4BetweenRange(_diffuseFront,0.0f,1.0f,"Material::setDiffuse(..)");
break;
case(BACK):
_diffuseFrontAndBack = false;
_diffuseBack = diffuse;
clampArray4BetweenRange(_diffuseBack,0.0f,1.0f,"Material::setDiffuse(..)");
//clampArray4BetweenRange(_diffuseBack,0.0f,1.0f,"Material::setDiffuse(..)");
break;
case(FRONT_AND_BACK):
_diffuseFrontAndBack = true;
_diffuseFront = diffuse;
clampArray4BetweenRange(_diffuseFront,0.0f,1.0f,"Material::setDiffuse(..)");
//clampArray4BetweenRange(_diffuseFront,0.0f,1.0f,"Material::setDiffuse(..)");
_diffuseBack = _diffuseFront;
break;
default:
@ -148,17 +148,17 @@ void Material::setSpecular(Face face, const Vec4& specular )
case(FRONT):
_specularFrontAndBack = false;
_specularFront = specular;
clampArray4BetweenRange(_specularFront,0.0f,1.0f,"Material::setSpecular(..)");
//clampArray4BetweenRange(_specularFront,0.0f,1.0f,"Material::setSpecular(..)");
break;
case(BACK):
_specularFrontAndBack = false;
_specularBack = specular;
clampArray4BetweenRange(_specularBack,0.0f,1.0f,"Material::setSpecular(..)");
//clampArray4BetweenRange(_specularBack,0.0f,1.0f,"Material::setSpecular(..)");
break;
case(FRONT_AND_BACK):
_specularFrontAndBack = true;
_specularFront = specular;
clampArray4BetweenRange(_specularFront,0.0f,1.0f,"Material::setSpecular(..)");
//clampArray4BetweenRange(_specularFront,0.0f,1.0f,"Material::setSpecular(..)");
_specularBack = _specularFront;
break;
default:
@ -196,17 +196,17 @@ void Material::setEmission(Face face, const Vec4& emission )
case(FRONT):
_emissionFrontAndBack = false;
_emissionFront = emission;
clampArray4BetweenRange(_emissionFront,0.0f,1.0f,"Material::setEmission(..)");
//clampArray4BetweenRange(_emissionFront,0.0f,1.0f,"Material::setEmission(..)");
break;
case(BACK):
_emissionFrontAndBack = false;
_emissionBack = emission;
clampArray4BetweenRange(_emissionBack,0.0f,1.0f,"Material::setEmission(..)");
//clampArray4BetweenRange(_emissionBack,0.0f,1.0f,"Material::setEmission(..)");
break;
case(FRONT_AND_BACK):
_emissionFrontAndBack = true;
_emissionFront = emission;
clampArray4BetweenRange(_emissionFront,0.0f,1.0f,"Material::setEmission(..)");
//clampArray4BetweenRange(_emissionFront,0.0f,1.0f,"Material::setEmission(..)");
_emissionBack = _emissionFront;
break;
default:
@ -285,7 +285,7 @@ float Material::getShininess(Face face) const
void Material::setTransparency(Face face,float transparency)
{
clampBetweenRange(transparency,0.0f,1.0f,"Material::setTransparency()");
//clampBetweenRange(transparency,0.0f,1.0f,"Material::setTransparency()");
if (face==FRONT || face==FRONT_AND_BACK)
{

View File

@ -16,7 +16,8 @@
using namespace osg;
NodeVisitor::NodeVisitor(TraversalMode tm)
NodeVisitor::NodeVisitor(TraversalMode tm):
Referenced()
{
_visitorType = NODE_VISITOR;
_traversalNumber = -1;
@ -26,7 +27,8 @@ NodeVisitor::NodeVisitor(TraversalMode tm)
_nodeMaskOverride = 0x0;
}
NodeVisitor::NodeVisitor(VisitorType type,TraversalMode tm)
NodeVisitor::NodeVisitor(VisitorType type,TraversalMode tm):
Referenced()
{
_visitorType = type;
_traversalNumber = -1;

View File

@ -55,7 +55,10 @@ Point::Point()
_size = 1.0f; // TODO find proper default
_fadeThresholdSize = 1.0f; // TODO find proper default
// TODO find proper default
_distanceAttenuation = Vec3(0.0f, 1.0f/5.f, 0.0f);
_distanceAttenuation = Vec3(1, 0.0, 0.0);
_minSize = 0.0;
_maxSize = 100.0;//depends on mulitsampling ... some default necessary
}
@ -99,6 +102,15 @@ void Point::setDistanceAttenuation(const Vec3& distanceAttenuation)
_distanceAttenuation = distanceAttenuation;
}
void Point::setMinSize(float minSize)
{
_minSize = minSize;
}
void Point::setMaxSize(float maxSize)
{
_maxSize = maxSize;
}
void Point::apply(State&) const
{
@ -112,8 +124,14 @@ void Point::apply(State&) const
init_GL_EXT();
}
if (s_PointParameterfvEXT) s_PointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT, (const GLfloat*)&_distanceAttenuation);
if (s_PointParameterfEXT) s_PointParameterfEXT(GL_POINT_FADE_THRESHOLD_SIZE_EXT, _fadeThresholdSize);
if (s_PointParameterfvEXT) s_PointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT, (const GLfloat*)&_distanceAttenuation);
if (s_PointParameterfEXT)
{
s_PointParameterfEXT(GL_POINT_FADE_THRESHOLD_SIZE_EXT, _fadeThresholdSize);
s_PointParameterfEXT(GL_POINT_SIZE_MIN_EXT, _minSize);
s_PointParameterfEXT(GL_POINT_SIZE_MAX_EXT, _maxSize);
}
}

View File

@ -16,6 +16,7 @@
#include <osg/GLExtensions>
using namespace std;
using namespace osg;
State::State()
@ -726,7 +727,7 @@ bool State::checkGLErrors(StateAttribute::GLMode mode) const
GLenum errorNo = glGetError();
if (errorNo!=GL_NO_ERROR)
{
osg::notify(WARN)<<"Warning: detected OpenGL error '"<<gluErrorString(errorNo)<<"' after applying GLMode "<<mode<< std::endl;
osg::notify(WARN)<<"Warning: detected OpenGL error '"<<gluErrorString(errorNo)<<"' after applying GLMode 0x"<<hex<<mode<<dec<< std::endl;
return true;
}
return false;

View File

@ -49,14 +49,18 @@ void TexEnvCombine::apply(State&) const
static bool s_isTexEnvCrossbarSupported =
isGLExtensionSupported("GL_ARB_texture_env_crossbar");
static bool s_isNVTexEnvCrossbarSupported =
isGLExtensionSupported("GL_NV_texture_env_combine4");
static bool s_isTexEnvDot3Supported =
isGLExtensionSupported("GL_ARB_texture_env_dot3");
bool needsTexEnvDot3 = (_combine_RGB==DOT3_RGB) ||
(_combine_RGB==DOT3_RGBA);
bool supported = s_isTexEnvCombineSupported;
if (_needsTexEnvCrossbar && !s_isTexEnvCrossbarSupported) supported = false;
if (_needsTexEnvCrossbar && !(s_isTexEnvCrossbarSupported || s_isNVTexEnvCrossbarSupported)) supported = false;
if (needsTexEnvDot3 && !s_isTexEnvDot3Supported) supported = false;
if (supported)

View File

@ -23,6 +23,11 @@ TextureRectangle::TextureRectangle():
_textureWidth(0),
_textureHeight(0)
{
setWrap(WRAP_S, CLAMP);
setWrap(WRAP_T, CLAMP);
setFilter(MIN_FILTER, LINEAR);
setFilter(MAG_FILTER, LINEAR);
}
TextureRectangle::TextureRectangle(const TextureRectangle& text,const CopyOp& copyop):
@ -132,7 +137,7 @@ void TextureRectangle::apply(State& state) const
applyTexParameters(GL_TEXTURE_RECTANGLE_NV, state);
applyTexImageRectangle(GL_TEXTURE_RECTANGLE_NV, _image.get(), state, _textureWidth, _textureHeight);
applyTexImage(GL_TEXTURE_RECTANGLE_NV, _image.get(), state, _textureWidth, _textureHeight);
// in theory the following line is redundant, but in practice
// have found that the first frame drawn doesn't apply the textures
@ -146,7 +151,22 @@ void TextureRectangle::apply(State& state) const
}
}
void TextureRectangle::applyTexImageRectangle(GLenum target, Image* image, State& state, GLsizei& inwidth, GLsizei& inheight) const
void TextureRectangle::applyTexParameters(GLenum target, State& state) const
{
// get the contextID (user defined ID of 0 upwards) for the
// current OpenGL context.
const unsigned int contextID = state.getContextID();
glTexParameteri( target, GL_TEXTURE_WRAP_S, _wrap_s );
glTexParameteri( target, GL_TEXTURE_WRAP_T, _wrap_t );
glTexParameteri( target, GL_TEXTURE_MIN_FILTER, _min_filter);
glTexParameteri( target, GL_TEXTURE_MAG_FILTER, _mag_filter);
getTextureParameterDirty(contextID) = false;
}
void TextureRectangle::applyTexImage(GLenum target, Image* image, State& state, GLsizei& inwidth, GLsizei& inheight) const
{
// if we don't have a valid image we can't create a texture!
if (!image || !image->data())

View File

@ -51,7 +51,8 @@ Registry* Registry::instance()
// definition of the Registry
Registry::Registry()
{
notify(INFO) << "Constructing osg::Registry"<<std::endl;
// comment out because it was causing problems under OSX - causing it to crash osgconv when constucting ostream in osg::notify().
// notify(INFO) << "Constructing osg::Registry"<<std::endl;
_createNodeFromImage = true;
_openingLibrary = false;
@ -126,16 +127,16 @@ void Registry::initDataFilePathList()
char *ptr;
if( (ptr = getenv( "OSG_FILE_PATH" )) )
{
notify(DEBUG_INFO) << "OSG_FILE_PATH("<<ptr<<")"<<std::endl;
//notify(DEBUG_INFO) << "OSG_FILE_PATH("<<ptr<<")"<<std::endl;
setDataFilePathList(ptr);
}
else if( (ptr = getenv( "OSGFILEPATH" )) )
{
notify(DEBUG_INFO) << "OSGFILEPATH("<<ptr<<")"<<std::endl;
//notify(DEBUG_INFO) << "OSGFILEPATH("<<ptr<<")"<<std::endl;
setDataFilePathList(ptr);
}
osg::notify(INFO)<<"Data FilePathList"<<std::endl;
//osg::notify(INFO)<<"Data FilePathList"<<std::endl;
PrintFilePathList(osg::notify(INFO),getDataFilePathList());
}
@ -153,12 +154,12 @@ void Registry::initLibraryFilePathList()
char* ptr;
if( (ptr = getenv( "OSG_LIBRARY_PATH")) )
{
notify(DEBUG_INFO) << "OSG_LIBRARY_PATH("<<ptr<<")"<<std::endl;
//notify(DEBUG_INFO) << "OSG_LIBRARY_PATH("<<ptr<<")"<<std::endl;
setLibraryFilePathList(ptr);
}
else if( (ptr = getenv( "OSG_LD_LIBRARY_PATH")) )
{
notify(DEBUG_INFO) << "OSG_LD_LIBRARY_PATH("<<ptr<<")"<<std::endl;
//notify(DEBUG_INFO) << "OSG_LD_LIBRARY_PATH("<<ptr<<")"<<std::endl;
setLibraryFilePathList(ptr);
}
@ -227,8 +228,8 @@ void Registry::initLibraryFilePathList()
#endif
osg::notify(INFO)<<"Library FilePathList"<<std::endl;
PrintFilePathList(osg::notify(INFO),getLibraryFilePathList());
//osg::notify(INFO)<<"Library FilePathList"<<std::endl;
//PrintFilePathList(osg::notify(INFO),getLibraryFilePathList());
}

View File

@ -3,7 +3,7 @@
void osgGA::GUIEventHandlerVisitor::visit(osgGA::CompositeGUIEventHandler& cgeh)
{
for(int i=0; i<cgeh.getNumChildren(); i++){
for(unsigned int i=0; i<cgeh.getNumChildren(); i++){
cgeh.getChild(i)->accept(*this);
}
}

View File

@ -105,7 +105,8 @@ class ReaderWriter3DC : public osgDB::ReaderWriter
//std::cout <<line<<std::endl;
//std::cout <<"]"<<std::endl;
}
geometry->setUseDisplayList(false);
geometry->setVertexArray(vertices);
geometry->setNormalArray(normals);
geometry->setNormalBinding(osg::Geometry::BIND_PER_VERTEX);

View File

@ -156,8 +156,11 @@ osg::Image* ReadDDSFile(const char *filename)
fread(&ddsd, sizeof(ddsd), 1, fp);
// Read image data.
unsigned int size = ddsd.dwMipMapCount > 1 ? ddsd.dwLinearSize * 2 : ddsd.dwLinearSize;
unsigned char* imageData = new unsigned char [size];
unsigned int size = ddsd.dwMipMapCount > 1 ? ddsd.dwLinearSize * (ddsd.ddpfPixelFormat.dwFourCC==FOURCC_DXT1 ? 2: 4) : ddsd.dwLinearSize;
//###################unsigned int size = ddsd.dwMipMapCount > 1 ? ddsd.dwLinearSize * 2 : ddsd.dwLinearSize;
unsigned char* imageData = new unsigned char [size];
fread(imageData, 1, size, fp);
// Close the file.
fclose(fp);
@ -206,7 +209,8 @@ osg::Image* ReadDDSFile(const char *filename)
else
{
internalFormat = GL_COMPRESSED_RGB_S3TC_DXT1_EXT;
pixelFormat = GL_COMPRESSED_RGB_S3TC_DXT1_EXT;
//#######################pixelFormat = GL_COMPRESSED_RGB_S3TC_DXT1_EXT;
pixelFormat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
}
break;
case FOURCC_DXT3:

View File

@ -113,7 +113,7 @@ void DynGeoSet::addToGeometry(osg::Geometry* geom)
{
int indexBase = 0;
osg::Vec3Array* vertices = geom->getVertexArray();
osg::Vec3Array* vertices = dynamic_cast<osg::Vec3Array*>(geom->getVertexArray());
if (vertices)
{
indexBase = vertices->size();

View File

@ -1838,11 +1838,25 @@ void ConvertFromFLT::visitLightPoint(GeoSetBuilder* pBuilder, LightPointRecord*
osg::Point* point = new osg::Point;
if (point)
{
/*
point->setSize(pSLightPoint->sfSize);
stateSet->setAttributeAndModes( point, osg::StateAttribute::ON );
// point->setFadeThresholdSize(const float fadeThresholdSize);
// point->setDistanceAttenuation(const Vec3& distanceAttenuation);
// point->setStateSetModes(*stateSet, osg::StateAttribute::ON); // GL_POINT_SMOOTH
*/
//change to:
point->setSize(pSLightPoint->afActualPixelSize);
point->setFadeThresholdSize(pSLightPoint->sfTranspFalloff);
//numbers that are going to appear are "experimental"
point->setDistanceAttenuation(osg::Vec3(0.0001, 0.0005, 0.00000025));
point->setMinSize(pSLightPoint->sfMinPixelSize);
point->setMaxSize(pSLightPoint->sfMaxPixelSize);
stateSet->setAttributeAndModes( point, osg::StateAttribute::ON );
stateSet->setMode(GL_POINT_SMOOTH, osg::StateAttribute::ON);
stateSet->setAttributeAndModes(new osg::BlendFunc, osg::StateAttribute::ON);
}

View File

@ -12,7 +12,7 @@
*/
#include "FreeTypeFont.h"
#include FT_GLYPH_H
//#include FT_GLYPH_H
#include <osg/Notify>
#include <osgDB/WriteFile>
@ -140,7 +140,7 @@ osg::Vec2 FreeTypeFont::getKerning(unsigned int leftcharcode,unsigned int rightc
FT_Error error = FT_Get_Kerning( _face, // handle to face object
left, // left glyph index
right, // right glyph index
ft_kerning_default, // kerning mode
FT_KERNING_UNFITTED, // kerning mode
&kerning ); // target vector
if (error)

View File

@ -36,10 +36,15 @@ void AnimationPathCallback::write(DataOutputStream* out){
out->writeDouble(_firstTime);
out->writeDouble(_animationTime);
// Write animationpath if any
out->writeInt((int)getAnimationPath());
if(getAnimationPath()){
if(getAnimationPath())
{
out->writeInt(1); // true we have an animation path.
((ive::AnimationPath*)(getAnimationPath()))->write(out);
}
else
{
out->writeInt(0); // false we don't have an animation path.
}
}
void AnimationPathCallback::read(DataInputStream* in){
@ -61,7 +66,8 @@ void AnimationPathCallback::read(DataInputStream* in){
_firstTime = in->readDouble();
_animationTime = in->readDouble();
// Read animationpath if any
if(in->readInt()){
if(in->readInt())
{
osg::AnimationPath* path = new osg::AnimationPath();
((ive::AnimationPath*)(path))->read(in);
setAnimationPath(path);

View File

@ -1,77 +1,113 @@
/**********************************************************************
*
* FILE: DataInputStream.cpp
* FILE: DataInputStream.cpp
*
* DESCRIPTION: Implements methods to read simpel datatypes from an
* input stream.
* DESCRIPTION: Implements methods to read simpel datatypes from an
* input stream.
*
* CREATED BY: Rune Schmidt Jensen
* CREATED BY: Rune Schmidt Jensen
*
* HISTORY: Created 11.03.2003
* HISTORY: Created 11.03.2003
*
* Copyright 2003 VR-C
* Copyright 2003 VR-C
**********************************************************************/
#include "DataInputStream.h"
#include "StateSet.h"
#include "BlendFunc.h"
#include "Material.h"
#include "CullFace.h"
#include "PolygonOffset.h"
#include "ShadeModel.h"
#include "Point.h"
#include "Texture2D.h"
#include "TextureCubeMap.h"
#include "TexEnv.h"
#include "TexEnvCombine.h"
#include "TexGen.h"
#include "Group.h"
#include "MatrixTransform.h"
#include "Geode.h"
#include "LightSource.h"
#include "Billboard.h"
#include "Sequence.h"
#include "LOD.h"
//#include "ViewPoint.h"
#include "PositionAttitudeTransform.h"
#include "Transform.h"
#include "Switch.h"
#include "OccluderNode.h"
#include "Impostor.h"
#include "Geometry.h"
#include <osgDB/ReadFile>
using namespace ive;
using namespace std;
DataInputStream::DataInputStream(std::istream* istream){
_istream = istream;
_peeking = false;
_peekValue = 0;
_istream = istream;
_peeking = false;
_peekValue = 0;
if(!istream){
throw Exception("DataInputStream::DataInputStream(): null pointer exception in argument.");
}
if(!istream){
throw Exception("DataInputStream::DataInputStream(): null pointer exception in argument.");
}
_version = readInt();
_version = readInt();
// Are we trying to open a binary .ive file which version are newer than this library.
if(_version>VERSION){
throw Exception("DataInputStream::DataInputStream(): The version found in the file is newer than this library can handle.");
}
// Are we trying to open a binary .ive file which version are newer than this library.
if(_version>VERSION){
throw Exception("DataInputStream::DataInputStream(): The version found in the file is newer than this library can handle.");
}
}
DataInputStream::~DataInputStream(){}
bool DataInputStream::readBool(){
bool b;
_istream->read((char*)&b, BOOLSIZE);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readBool(): Failed to read boolean value.");
return b;
bool b;
_istream->read((char*)&b, BOOLSIZE);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readBool(): Failed to read boolean value.");
return b;
}
char DataInputStream::readChar(){
char c;
_istream->read(&c, CHARSIZE);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readChar(): Failed to read char value.");
return c;
char c;
_istream->read(&c, CHARSIZE);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readChar(): Failed to read char value.");
return c;
}
unsigned short DataInputStream::readUShort(){
unsigned short s;
_istream->read((char*)&s, SHORTSIZE);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readUShort(): Failed to read unsigned short value.");
return s;
unsigned short s;
_istream->read((char*)&s, SHORTSIZE);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readUShort(): Failed to read unsigned short value.");
return s;
}
unsigned int DataInputStream::readUInt(){
unsigned int s;
_istream->read((char*)&s, INTSIZE);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readUInt(): Failed to read unsigned int value.");
return s;
}
int DataInputStream::readInt(){
if(_peeking){
_peeking = false;
return _peekValue;
}
int i;
_istream->read((char*)&i, INTSIZE);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readInt(): Failed to read int value.");
return i;
if(_peeking){
_peeking = false;
return _peekValue;
}
int i;
_istream->read((char*)&i, INTSIZE);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readInt(): Failed to read int value.");
return i;
}
/**
@ -80,247 +116,476 @@ int DataInputStream::readInt(){
* return the same integer.
*/
int DataInputStream::peekInt(){
if(_peeking){
return _peekValue;
}
_peekValue = readInt();
_peeking = true;
return _peekValue;
if(_peeking){
return _peekValue;
}
_peekValue = readInt();
_peeking = true;
return _peekValue;
}
float DataInputStream::readFloat(){
float f;
_istream->read((char*)&f, FLOATSIZE);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readFloat(): Failed to read float value.");
return f;
float f;
_istream->read((char*)&f, FLOATSIZE);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readFloat(): Failed to read float value.");
return f;
}
long DataInputStream::readLong(){
long l;
_istream->read((char*)&l, LONGSIZE);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readLong(): Failed to read long value.");
return l;
long l;
_istream->read((char*)&l, LONGSIZE);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readLong(): Failed to read long value.");
return l;
}
double DataInputStream::readDouble(){
double d;
_istream->read((char*)&d, DOUBLESIZE);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readDouble(): Failed to read double value.");
return d;
double d;
_istream->read((char*)&d, DOUBLESIZE);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readDouble(): Failed to read double value.");
return d;
}
std::string DataInputStream::readString(){
std::string s;
int size = readInt();
s.resize(size);
_istream->read((char*)s.c_str(), size);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readString(): Failed to read string value.");
return s;
std::string s;
int size = readInt();
s.resize(size);
_istream->read((char*)s.c_str(), size);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readString(): Failed to read string value.");
return s;
}
void DataInputStream::readCharArray(char* data, int size){
_istream->read(data, size);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readCharArray(): Failed to read char value.");
_istream->read(data, size);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readCharArray(): Failed to read char value.");
}
osg::Vec2 DataInputStream::readVec2(){
osg::Vec2 v;
v.set(readFloat(), readFloat());
return v;
osg::Vec2 v;
v.x()=readFloat();
v.y()=readFloat();
return v;
}
osg::Vec3 DataInputStream::readVec3(){
osg::Vec3 v;
v.set(readFloat(),readFloat(),readFloat());
return v;
osg::Vec3 v;
v.x()=readFloat();
v.y()=readFloat();
v.z()=readFloat();
return v;
}
osg::Vec4 DataInputStream::readVec4(){
osg::Vec4 v;
v.set(readFloat(), readFloat(), readFloat(), readFloat());
return v;
osg::Vec4 v;
v.x()=readFloat();
v.y()=readFloat();
v.z()=readFloat();
v.w()=readFloat();
return v;
}
osg::UByte4 DataInputStream::readUByte4(){
osg::UByte4 v;
v.set(readChar(), readChar(), readChar(), readChar());
return v;
osg::UByte4 v;
v.r()=readChar();
v.g()=readChar();
v.b()=readChar();
v.a()=readChar();
return v;
}
osg::Quat DataInputStream::readQuat(){
osg::Quat q;
q.set(readFloat(), readFloat(), readFloat(), readFloat());
return q;
osg::Quat q;
q.set(readFloat(), readFloat(), readFloat(), readFloat());
return q;
}
/**
*
*/
osg::Image* DataInputStream::readImage(std::string filename){
// If image is already read and in list
// then just return pointer to this.
for(ImageList::iterator mitr=_imageList.begin();
mitr!=_imageList.end(); ++mitr){
if(mitr->first.compare(filename) == 0){
return mitr->second.get();
}
}
// Image is not in list.
// Read it from disk,
osg::Image* image = osgDB::readImageFile(filename.c_str());
// add it to the imageList,
_imageList.push_back(ImagePair(filename, image));
// and return image pointer.
return image;
}
osg::StateSet* DataInputStream::readStateSet(){
// Read statesets unique ID.
int id = readInt();
// See if stateset is already in the list.
for(StateSetList::iterator itr=_statesetList.begin();
itr!=_statesetList.end(); ++itr){
if(itr->first == id){
return itr->second.get();
}
}
// StateSet is not in list.
// Create a new stateset,
osg::StateSet* stateset = new osg::StateSet();
// read its properties from stream
((ive::StateSet*)(stateset))->read(this);
// and add it to the stateset list,
_statesetList.push_back(StateSetPair(id, stateset));
return stateset;
}
osg::Geometry::AttributeBinding DataInputStream::readBinding(){
char c = readChar();
switch((int)c){
case 0: return osg::Geometry::BIND_OFF;
case 1: return osg::Geometry::BIND_OVERALL;
case 2: return osg::Geometry::BIND_PER_PRIMITIVE;
case 3: return osg::Geometry::BIND_PER_PRIMITIVE_SET;
case 4: return osg::Geometry::BIND_PER_VERTEX;
default: throw Exception("Unknown binding type in DataInputStream::readBinding()");
}
char c = readChar();
switch((int)c){
case 0: return osg::Geometry::BIND_OFF;
case 1: return osg::Geometry::BIND_OVERALL;
case 2: return osg::Geometry::BIND_PER_PRIMITIVE;
case 3: return osg::Geometry::BIND_PER_PRIMITIVE_SET;
case 4: return osg::Geometry::BIND_PER_VERTEX;
default: throw Exception("Unknown binding type in DataInputStream::readBinding()");
}
}
osg::Array* DataInputStream::readArray(){
char c = readChar();
switch((int)c){
case 0: return readIntArray();
case 1: return readUByteArray();
case 2: return readUShortArray();
case 3: return readUIntArray();
case 4: return readUByte4Array();
case 5: return readFloatArray();
case 6: return readVec2Array();
case 7: return readVec3Array();
case 8: return readVec4Array();
default: throw Exception("Unknown array type in DataInputStream::readArray()");
}
char c = readChar();
switch((int)c){
case 0: return readIntArray();
case 1: return readUByteArray();
case 2: return readUShortArray();
case 3: return readUIntArray();
case 4: return readUByte4Array();
case 5: return readFloatArray();
case 6: return readVec2Array();
case 7: return readVec3Array();
case 8: return readVec4Array();
default: throw Exception("Unknown array type in DataInputStream::readArray()");
}
}
osg::IntArray* DataInputStream::readIntArray(){
int size = readInt();
osg::IntArray* a = new osg::IntArray();
a->reserve(size);
for(int i =0; i<size;i++){
a->push_back(readInt());
}
return a;
int size = readInt();
osg::IntArray* a = new osg::IntArray(size);
_istream->read((char*)&((*a)[0]), INTSIZE*size);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readIntArray(): Failed to read Int array.");
// a->reserve(size);
// for(int i =0; i<size;i++){
// a->push_back(readInt());
// }
return a;
}
osg::UByteArray* DataInputStream::readUByteArray(){
int size = readInt();
osg::UByteArray* a = new osg::UByteArray();
a->reserve(size);
for(int i =0; i<size;i++){
a->push_back(readChar());
}
return a;
int size = readInt();
osg::UByteArray* a = new osg::UByteArray(size);
_istream->read((char*)&((*a)[0]), CHARSIZE*size);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readUByteArray(): Failed to read UByte array.");
// a->reserve(size);
// for(int i =0; i<size;i++){
// a->push_back(readChar());
// }
return a;
}
osg::UShortArray* DataInputStream::readUShortArray(){
int size = readInt();
osg::UShortArray* a = new osg::UShortArray();
a->reserve(size);
for(int i =0; i<size;i++){
a->push_back(readUShort());
}
return a;
int size = readInt();
osg::UShortArray* a = new osg::UShortArray(size);
_istream->read((char*)&((*a)[0]), SHORTSIZE*size);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readUShortArray(): Failed to read UShort array.");
//
// a->reserve(size);
// for(int i =0; i<size;i++){
// a->push_back(readUShort());
// }
return a;
}
osg::UIntArray* DataInputStream::readUIntArray(){
int size = readInt();
osg::UIntArray* a = new osg::UIntArray();
a->reserve(size);
for(int i =0; i<size;i++){
a->push_back((unsigned int)readInt());
}
return a;
int size = readInt();
osg::UIntArray* a = new osg::UIntArray(size);
_istream->read((char*)&((*a)[0]), INTSIZE*size);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readUIntArray(): Failed to read UInt array.");
//
// a->reserve(size);
// for(int i =0; i<size;i++){
// a->push_back((unsigned int)readInt());
// }
return a;
}
osg::UByte4Array* DataInputStream::readUByte4Array(){
int size = readInt();
osg::UByte4Array* a = new osg::UByte4Array();
a->reserve(size);
for(int i =0; i<size;i++){
a->push_back(readUByte4());
}
return a;
int size = readInt();
osg::UByte4Array* a = new osg::UByte4Array(size);
_istream->read((char*)&((*a)[0]), INTSIZE*size);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readUbyte4Array(): Failed to read UByte4 array.");
// a->reserve(size);
// for(int i =0; i<size;i++){
// a->push_back(readUByte4());
// }
return a;
}
osg::FloatArray* DataInputStream::readFloatArray(){
int size = readInt();
osg::FloatArray* a = new osg::FloatArray();
a->reserve(size);
for(int i =0; i<size;i++){
a->push_back(readFloat());
}
return a;
int size = readInt();
osg::FloatArray* a = new osg::FloatArray(size);
_istream->read((char*)&((*a)[0]), FLOATSIZE*size);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readFloatArray(): Failed to read float array.");
// a->reserve(size);
// for(int i =0; i<size;i++){
// a->push_back(readFloat());
// }
return a;
}
osg::Vec2Array* DataInputStream::readVec2Array(){
int size = readInt();
osg::Vec2Array* a = new osg::Vec2Array(size);
for(int i = 0; i < size; i++){
(*a)[i] = (readVec2());
}
return a;
int size = readInt();
osg::Vec2Array* a = new osg::Vec2Array(size);
_istream->read((char*)&((*a)[0]), FLOATSIZE*2*size);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readVec2Array(): Failed to read Vec2 array.");
// for(int i = 0; i < size; i++){
// (*a)[i] = (readVec2());
// }
return a;
}
osg::Vec3Array* DataInputStream::readVec3Array(){
int size = readInt();
osg::Vec3Array* a = new osg::Vec3Array(size);
for(int i = 0; i < size; i++){
(*a)[i] = readVec3();
}
return a;
int size = readInt();
osg::Vec3Array* a = new osg::Vec3Array(size);
_istream->read((char*)&((*a)[0]), FLOATSIZE*3*size);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readVec3Array(): Failed to read Vec3 array.");
// for(int i = 0; i < size; i++){
// (*a)[i] = readVec3();
// }
return a;
}
osg::Vec4Array* DataInputStream::readVec4Array(){
int size = readInt();
osg::Vec4Array* a = new osg::Vec4Array(size);
for(int i = 0; i < size; i++){
(*a)[i] = (readVec4());
}
return a;
int size = readInt();
osg::Vec4Array* a = new osg::Vec4Array(size);
_istream->read((char*)&((*a)[0]), FLOATSIZE*4*size);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readVec4Array(): Failed to read Vec4 array.");
// for(int i = 0; i < size; i++){
// (*a)[i] = (readVec4());
// }
return a;
}
osg::Matrix DataInputStream::readMatrix(){
osg::Matrix mat;
float* p = mat.ptr();
for(int i=0;i<16;i++){
p[i] = readFloat();
}
return mat;
osg::Matrix mat;
_istream->read((char*)(mat.ptr()), FLOATSIZE*16);
if (_istream->rdstate() & _istream->failbit)
throw Exception("DataInputStream::readMatrix(): Failed to read Matrix array.");
// float* p = mat.ptr();
// for(int i=0;i<16;i++){
// p[i] = readFloat();
// }
return mat;
}
osg::Image* DataInputStream::readImage(std::string filename)
{
// If image is already read and in list
// then just return pointer to this.
ImageMap::iterator mitr=_imageMap.find(filename);
if (mitr!=_imageMap.end()) mitr->second.get();
// Image is not in list.
// Read it from disk,
osg::Image* image = osgDB::readImageFile(filename.c_str());
// add it to the imageList,
_imageMap[filename] = image;
// and return image pointer.
return image;
}
osg::StateSet* DataInputStream::readStateSet()
{
// Read statesets unique ID.
int id = readInt();
// See if stateset is already in the list.
StateSetMap::iterator itr= _statesetMap.find(id);
if (itr!=_statesetMap.end()) return itr->second.get();
// StateSet is not in list.
// Create a new stateset,
osg::StateSet* stateset = new osg::StateSet();
// read its properties from stream
((ive::StateSet*)(stateset))->read(this);
// and add it to the stateset map,
_statesetMap[id] = stateset;
return stateset;
}
osg::StateAttribute* DataInputStream::readStateAttribute()
{
// Read stateattributes unique ID.
int id = readInt();
// See if stateattribute is already in the list.
StateAttributeMap::iterator itr= _stateAttributeMap.find(id);
if (itr!=_stateAttributeMap.end()) return itr->second.get();
// stateattribute is not in list.
// Create a new stateattribute,
osg::StateAttribute* attribute;
int attributeID = peekInt();
if(attributeID == IVEBLENDFUNC){
attribute = new osg::BlendFunc();
((ive::BlendFunc*)(attribute))->read(this);
}
else if(attributeID == IVEMATERIAL){
attribute = new osg::Material();
((ive::Material*)(attribute))->read(this);
}
else if(attributeID == IVECULLFACE){
attribute = new osg::CullFace();
((ive::CullFace*)(attribute))->read(this);
}
else if(attributeID == IVEPOLYGONOFFSET){
attribute = new osg::PolygonOffset();
((ive::PolygonOffset*)(attribute))->read(this);
}
else if(attributeID == IVESHADEMODEL){
attribute = new osg::ShadeModel();
((ive::ShadeModel*)(attribute))->read(this);
}
else if(attributeID == IVEPOINT){
attribute = new osg::Point();
((ive::Point*)(attribute))->read(this);
}
else if(attributeID == IVETEXTURE2D){
attribute = new osg::Texture2D();
((ive::Texture2D*)(attribute))->read(this);
}
else if(attributeID == IVETEXTURECUBEMAP){
attribute = new osg::TextureCubeMap();
((ive::TextureCubeMap*)(attribute))->read(this);
}
else if(attributeID == IVETEXENV){
attribute = new osg::TexEnv();
((ive::TexEnv*)(attribute))->read(this);
}
else if(attributeID == IVETEXENVCOMBINE){
attribute = new osg::TexEnvCombine();
((ive::TexEnvCombine*)(attribute))->read(this);
}
else if(attributeID == IVETEXGEN){
attribute = new osg::TexGen();
((ive::TexGen*)(attribute))->read(this);
}
else{
throw Exception("Unkown StateAttribute in StateSet::read()");
}
// and add it to the stateattribute map,
_stateAttributeMap[id] = attribute;
return attribute;
}
osg::Drawable* DataInputStream::readDrawable()
{
// Read stateattributes unique ID.
int id = readInt();
// See if stateattribute is already in the list.
DrawableMap::iterator itr= _drawableMap.find(id);
if (itr!=_drawableMap.end()) return itr->second.get();
// stateattribute is not in list.
// Create a new stateattribute,
int drawableTypeID = peekInt();
osg::Drawable* drawable;
if(drawableTypeID == IVEGEOMETRY){
drawable = new osg::Geometry();
((Geometry*)(drawable))->read(this);
}
else
throw Exception("Unknown drawable drawableTypeIDentification in Geode::read()");
// and add it to the stateattribute map,
_drawableMap[id] = drawable;
return drawable;
}
osg::Node* DataInputStream::readNode()
{
// Read node unique ID.
int id = readInt();
// See if node is already in the list.
NodeMap::iterator itr= _nodeMap.find(id);
if (itr!=_nodeMap.end()) return itr->second.get();
// stateattribute is not in list.
// Create a new node,
osg::Node* node;
int nodeTypeID= peekInt();
if(nodeTypeID== IVEMATRIXTRANSFORM){
node = new osg::MatrixTransform();
((ive::MatrixTransform*)(node))->read(this);
}
// else if(nodeTypeID== IVEVIEWPOINT){
// node = new osgfIVE::ViewPoint();
// ((ive::ViewPoint*)(node))->read(this);
// }
else if(nodeTypeID== IVEPOSITIONATTITUDETRANSFORM){
node = new osg::PositionAttitudeTransform();
((ive::PositionAttitudeTransform*)(node))->read(this);
}
else if(nodeTypeID== IVETRANSFORM){
node = new osg::Transform();
((ive::Transform*)(node))->read(this);
}
else if(nodeTypeID== IVELIGHTSOURCE){
node = new osg::LightSource();
((ive::LightSource*)(node))->read(this);
}
else if(nodeTypeID== IVESEQUENCE){
node = new osg::Sequence();
((ive::Sequence*)(node))->read(this);
}
else if(nodeTypeID== IVELOD){
node = new osg::LOD();
((ive::LOD*)(node))->read(this);
}
else if(nodeTypeID== IVESWITCH){
node = new osg::Switch();
((ive::Switch*)(node))->read(this);
}
else if(nodeTypeID== IVEIMPOSTOR){
node = new osg::Impostor();
((ive::Impostor*)(node))->read(this);
}
else if(nodeTypeID== IVEOCCLUDERNODE){
node = new osg::OccluderNode();
((ive::OccluderNode*)(node))->read(this);
}
else if(nodeTypeID== IVEGROUP){
node = new osg::Group();
((ive::Group*)(node))->read(this);
}
else if(nodeTypeID== IVEBILLBOARD){
node = new osg::Billboard();
((ive::Billboard*)(node))->read(this);
}
else if(nodeTypeID== IVEGEODE){
node = new osg::Geode();
((ive::Geode*)(node))->read(this);
}
else{
throw Exception("Unknown node identification in DataInputStream::readNode()");
}
// and add it to the stateattribute map,
_nodeMap[id] = node;
return node;
}

View File

@ -32,6 +32,7 @@ public:
bool readBool();
char readChar();
unsigned short readUShort();
unsigned int readUInt();
int readInt();
int peekInt();
float readFloat();
@ -46,8 +47,6 @@ public:
osg::Quat readQuat();
osg::Matrix readMatrix();
osg::Geometry::AttributeBinding readBinding();
osg::Image* readImage(std::string s);
osg::StateSet* readStateSet();
osg::Array* readArray();
osg::IntArray* readIntArray();
osg::UByteArray* readUByteArray();
@ -59,22 +58,29 @@ public:
osg::Vec3Array* readVec3Array();
osg::Vec4Array* readVec4Array();
// Container to map image filenames to their respective images.
typedef std::pair<std::string, osg::ref_ptr<osg::Image> > ImagePair;
typedef std::vector<ImagePair> ImageList;
osg::Image* readImage(std::string s);
osg::StateSet* readStateSet();
osg::StateAttribute* readStateAttribute();
osg::Drawable* readDrawable();
osg::Node* readNode();
// Container to map stateset id to their respective stateset.
typedef std::pair<int, osg::ref_ptr<osg::StateSet> > StateSetPair;
typedef std::vector<StateSetPair> StateSetList;
typedef std::map<std::string, osg::ref_ptr<osg::Image> > ImageMap;
typedef std::map<int,osg::ref_ptr<osg::StateSet> > StateSetMap;
typedef std::map<int,osg::ref_ptr<osg::StateAttribute> > StateAttributeMap;
typedef std::map<int,osg::ref_ptr<osg::Drawable> > DrawableMap;
typedef std::map<int,osg::ref_ptr<osg::Node> > NodeMap;
private:
std::istream* _istream;
int _version;
bool _peeking;
int _peekValue;
ImageList _imageList;
StateSetList _statesetList;
std::istream* _istream;
int _version;
bool _peeking;
int _peekValue;
ImageMap _imageMap;
StateSetMap _statesetMap;
StateAttributeMap _stateAttributeMap;
DrawableMap _drawableMap;
NodeMap _nodeMap;
};
}

View File

@ -1,252 +1,449 @@
/**********************************************************************
*
* FILE: DataOutputStream.cpp
* FILE: DataOutputStream.cpp
*
* DESCRIPTION: Implements methods to write simpel datatypes to an
* output stream.
* DESCRIPTION: Implements methods to write simpel datatypes to an
* output stream.
*
* CREATED BY: Rune Schmidt Jensen
* CREATED BY: Rune Schmidt Jensen
*
* HISTORY: Created 11.03.2003
* HISTORY: Created 11.03.2003
*
* Copyright 2003 VR-C
* Copyright 2003 VR-C
**********************************************************************/
#include "DataOutputStream.h"
#include "Exception.h"
#include "StateSet.h"
#include "BlendFunc.h"
#include "Material.h"
#include "CullFace.h"
#include "PolygonOffset.h"
#include "ShadeModel.h"
#include "Point.h"
#include "Texture2D.h"
#include "TextureCubeMap.h"
#include "TexEnv.h"
#include "TexEnvCombine.h"
#include "TexGen.h"
#include "Group.h"
#include "MatrixTransform.h"
#include "Geode.h"
#include "LightSource.h"
#include "Billboard.h"
#include "Sequence.h"
#include "LOD.h"
//#include "ViewPoint.h"
#include "PositionAttitudeTransform.h"
#include "Transform.h"
#include "Switch.h"
#include "OccluderNode.h"
#include "Impostor.h"
#include "Geometry.h"
using namespace ive;
DataOutputStream::DataOutputStream(std::ostream * ostream){
_includeImageData= true;
_ostream = ostream;
if(!_ostream)
throw Exception("DataOutputStream::DataOutputStream(): null pointer exception in argument.");
writeInt(VERSION);
_includeImageData= true;
_ostream = ostream;
if(!_ostream)
throw Exception("DataOutputStream::DataOutputStream(): null pointer exception in argument.");
writeInt(VERSION);
}
DataOutputStream::~DataOutputStream(){}
void DataOutputStream::writeBool(bool b){
_ostream->write((char*)&b, BOOLSIZE);
_ostream->write((char*)&b, BOOLSIZE);
}
void DataOutputStream::writeChar(char c){
_ostream->write(&c, CHARSIZE);
_ostream->write(&c, CHARSIZE);
}
void DataOutputStream::writeUShort(unsigned short s){
_ostream->write((char*)&s, SHORTSIZE);
_ostream->write((char*)&s, SHORTSIZE);
}
void DataOutputStream::writeUInt(unsigned int s){
_ostream->write((char*)&s, INTSIZE);
}
void DataOutputStream::writeInt(int i){
_ostream->write((char*)&i, INTSIZE);
_ostream->write((char*)&i, INTSIZE);
}
void DataOutputStream::writeFloat(float f){
_ostream->write((char*)&f, FLOATSIZE);
_ostream->write((char*)&f, FLOATSIZE);
}
void DataOutputStream::writeLong(long l){
_ostream->write((char*)&l, LONGSIZE);
_ostream->write((char*)&l, LONGSIZE);
}
void DataOutputStream::writeDouble(double d){
_ostream->write((char*)&d, DOUBLESIZE);
_ostream->write((char*)&d, DOUBLESIZE);
}
void DataOutputStream::writeString(std::string s){
writeInt(s.size());
_ostream->write(s.c_str(), s.size());
writeInt(s.size());
_ostream->write(s.c_str(), s.size());
}
void DataOutputStream::writeCharArray(char* data, int size){
_ostream->write(data, size);
_ostream->write(data, size);
}
void DataOutputStream::writeVec2(osg::Vec2 v){
writeFloat(v.y());
writeFloat(v.x());
void DataOutputStream::writeVec2(const osg::Vec2& v){
writeFloat(v.x());
writeFloat(v.y());
}
void DataOutputStream::writeVec3(osg::Vec3 v){
writeFloat(v.z());
writeFloat(v.y());
writeFloat(v.x());
void DataOutputStream::writeVec3(const osg::Vec3& v){
writeFloat(v.x());
writeFloat(v.y());
writeFloat(v.z());
}
void DataOutputStream::writeVec4(osg::Vec4 v){
writeFloat(v.w());
writeFloat(v.z());
writeFloat(v.y());
writeFloat(v.x());
void DataOutputStream::writeVec4(const osg::Vec4& v){
writeFloat(v.x());
writeFloat(v.y());
writeFloat(v.z());
writeFloat(v.w());
}
void DataOutputStream::writeUByte4(osg::UByte4 v){
writeChar(v.a());
writeChar(v.b());
writeChar(v.g());
writeChar(v.r());
void DataOutputStream::writeUByte4(const osg::UByte4& v){
writeChar(v.r());
writeChar(v.g());
writeChar(v.b());
writeChar(v.a());
}
void DataOutputStream::writeQuat(osg::Quat q){
writeFloat(q.w());
writeFloat(q.z());
writeFloat(q.y());
writeFloat(q.x());
}
void DataOutputStream::writeStateSet(osg::StateSet* stateset){
// If stateset is already in list we do not write it again.
// We just writes its unique ID.
for(StateSetList::iterator itr=_statesetList.begin();
itr!=_statesetList.end(); ++itr){
if((*itr) == (int)stateset){
writeInt((*itr));
return;
}
}
// StateSet is not in list.
// We write its unique ID,
writeInt((int)stateset);
// add it to the stateset list,
_statesetList.push_back((int)stateset);
// and write it to stream.
((ive::StateSet*)(stateset))->write(this);
void DataOutputStream::writeQuat(const osg::Quat& q){
writeFloat(q.x());
writeFloat(q.y());
writeFloat(q.z());
writeFloat(q.w());
}
void DataOutputStream::writeBinding(osg::Geometry::AttributeBinding b){
switch(b){
case osg::Geometry::BIND_OFF: writeChar((char) 0); break;
case osg::Geometry::BIND_OVERALL: writeChar((char) 1); break;
case osg::Geometry::BIND_PER_PRIMITIVE: writeChar((char) 2); break;
case osg::Geometry::BIND_PER_PRIMITIVE_SET: writeChar((char) 3); break;
case osg::Geometry::BIND_PER_VERTEX: writeChar((char) 4); break;
default: throw Exception("Unknown binding in DataOutputStream::writeBinding()");
}
switch(b){
case osg::Geometry::BIND_OFF: writeChar((char) 0); break;
case osg::Geometry::BIND_OVERALL: writeChar((char) 1); break;
case osg::Geometry::BIND_PER_PRIMITIVE: writeChar((char) 2); break;
case osg::Geometry::BIND_PER_PRIMITIVE_SET: writeChar((char) 3); break;
case osg::Geometry::BIND_PER_VERTEX: writeChar((char) 4); break;
default: throw Exception("Unknown binding in DataOutputStream::writeBinding()");
}
}
void DataOutputStream::writeArray(osg::Array* a){
switch(a->getType()){
case osg::Array::IntArrayType:
writeChar((char)0);
writeIntArray(static_cast<osg::IntArray*>(a));
break;
case osg::Array::UByteArrayType:
writeChar((char)1);
writeUByteArray(static_cast<osg::UByteArray*>(a));
break;
case osg::Array::UShortArrayType:
writeChar((char)2);
writeUShortArray(static_cast<osg::UShortArray*>(a));
break;
case osg::Array::UIntArrayType:
writeChar((char)3);
writeUIntArray(static_cast<osg::UIntArray*>(a));
break;
case osg::Array::UByte4ArrayType:
writeChar((char)4);
writeUByte4Array(static_cast<osg::UByte4Array*>(a));
break;
case osg::Array::FloatArrayType:
writeChar((char)5);
writeFloatArray(static_cast<osg::FloatArray*>(a));
break;
case osg::Array::Vec2ArrayType:
writeChar((char)6);
writeVec2Array(static_cast<osg::Vec2Array*>(a));
break;
case osg::Array::Vec3ArrayType:
writeChar((char)7);
writeVec3Array(static_cast<osg::Vec3Array*>(a));
break;
case osg::Array::Vec4ArrayType:
writeChar((char)8);
writeVec4Array(static_cast<osg::Vec4Array*>(a));
break;
default: throw Exception("Unknown array type in DataOutputStream::writeArray()");
}
switch(a->getType()){
case osg::Array::IntArrayType:
writeChar((char)0);
writeIntArray(static_cast<osg::IntArray*>(a));
break;
case osg::Array::UByteArrayType:
writeChar((char)1);
writeUByteArray(static_cast<osg::UByteArray*>(a));
break;
case osg::Array::UShortArrayType:
writeChar((char)2);
writeUShortArray(static_cast<osg::UShortArray*>(a));
break;
case osg::Array::UIntArrayType:
writeChar((char)3);
writeUIntArray(static_cast<osg::UIntArray*>(a));
break;
case osg::Array::UByte4ArrayType:
writeChar((char)4);
writeUByte4Array(static_cast<osg::UByte4Array*>(a));
break;
case osg::Array::FloatArrayType:
writeChar((char)5);
writeFloatArray(static_cast<osg::FloatArray*>(a));
break;
case osg::Array::Vec2ArrayType:
writeChar((char)6);
writeVec2Array(static_cast<osg::Vec2Array*>(a));
break;
case osg::Array::Vec3ArrayType:
writeChar((char)7);
writeVec3Array(static_cast<osg::Vec3Array*>(a));
break;
case osg::Array::Vec4ArrayType:
writeChar((char)8);
writeVec4Array(static_cast<osg::Vec4Array*>(a));
break;
default: throw Exception("Unknown array type in DataOutputStream::writeArray()");
}
}
void DataOutputStream::writeIntArray(osg::IntArray* a){
int size = a->getNumElements();
writeInt(size);
for(int i =0; i<size ;i++){
writeInt(a->index(i));
}
int size = a->getNumElements();
writeInt(size);
for(int i =0; i<size ;i++){
writeInt(a->index(i));
}
}
void DataOutputStream::writeUByteArray(osg::UByteArray* a){
int size = a->getNumElements();
writeInt(size);
for(int i =0; i<size ;i++){
writeChar((*a)[i]);
}
int size = a->getNumElements();
writeInt(size);
for(int i =0; i<size ;i++){
writeChar((*a)[i]);
}
}
void DataOutputStream::writeUShortArray(osg::UShortArray* a){
int size = a->getNumElements();
writeInt(size);
for(int i =0; i<size ;i++){
writeUShort((*a)[i]);
}
int size = a->getNumElements();
writeInt(size);
for(int i =0; i<size ;i++){
writeUShort((*a)[i]);
}
}
void DataOutputStream::writeUIntArray(osg::UIntArray* a){
int size = a->getNumElements();
writeInt(size);
for(int i =0; i<size ;i++){
writeInt((*a)[i]);
}
int size = a->getNumElements();
writeInt(size);
for(int i =0; i<size ;i++){
writeInt((*a)[i]);
}
}
void DataOutputStream::writeUByte4Array(osg::UByte4Array* a){
int size = a->getNumElements();
writeInt(size);
for(int i =0; i<size ;i++){
writeUByte4((*a)[i]);
}
int size = a->getNumElements();
writeInt(size);
for(int i =0; i<size ;i++){
writeUByte4((*a)[i]);
}
}
void DataOutputStream::writeFloatArray(osg::FloatArray* a){
int size = a->getNumElements();
writeInt(size);
for(int i =0; i<size ;i++){
writeFloat((*a)[i]);
}
int size = a->getNumElements();
writeInt(size);
for(int i =0; i<size ;i++){
writeFloat((*a)[i]);
}
}
void DataOutputStream::writeVec2Array(osg::Vec2Array* a){
int size = a->size();
writeInt(size);
for(int i=0;i<size;i++){
writeVec2((*a)[i]);
}
int size = a->size();
writeInt(size);
for(int i=0;i<size;i++){
writeVec2((*a)[i]);
}
}
void DataOutputStream::writeVec3Array(osg::Vec3Array* a){
int size = a->size();
writeInt(size);
for(int i = 0; i < size; i++){
int size = a->size();
writeInt(size);
for(int i = 0; i < size; i++){
writeVec3((*a)[i]);
}
}
}
void DataOutputStream::writeVec4Array(osg::Vec4Array* a){
int size = a->size();
writeInt(size);
for(int i=0;i<size;i++){
writeVec4((*a)[i]);
}
int size = a->size();
writeInt(size);
for(int i=0;i<size;i++){
writeVec4((*a)[i]);
}
}
void DataOutputStream::writeMatrix(osg::Matrix mat){
float* p = mat.ptr();
for(int i=0;i<16;i++){
writeFloat(p[i]);
}
float* p = mat.ptr();
for(int i=0;i<16;i++){
writeFloat(p[i]);
}
}
void DataOutputStream::writeStateSet(osg::StateSet* stateset)
{
StateSetMap::iterator itr = _stateSetMap.find(stateset);
if (itr!=_stateSetMap.end())
{
// Id already exists so just write ID.
writeInt(itr->second);
}
else
{
// id doesn't exist so create a new ID and
// register the stateset.
int id = _stateSetMap.size();
_stateSetMap[stateset] = id;
// write the id.
writeInt(id);
// write the stateset.
((ive::StateSet*)(stateset))->write(this);
}
}
void DataOutputStream::writeStateAttribute(osg::StateAttribute* attribute)
{
StateAttributeMap::iterator itr = _stateAttributeMap.find(attribute);
if (itr!=_stateAttributeMap.end())
{
// Id already exists so just write ID.
writeInt(itr->second);
}
else
{
// id doesn't exist so create a new ID and
// register the stateset.
int id = _stateAttributeMap.size();
_stateAttributeMap[attribute] = id;
// write the id.
writeInt(id);
// write the stateset.
if(dynamic_cast<osg::BlendFunc*>(attribute)){
((ive::BlendFunc*)(attribute))->write(this);
}
// This is a Material
else if(dynamic_cast<osg::Material*>(attribute)){
((ive::Material*)(attribute))->write(this);
}
// This is a CullFace
else if(dynamic_cast<osg::CullFace*>(attribute)){
((ive::CullFace*)(attribute))->write(this);
}
// This is a PolygonOffset
else if(dynamic_cast<osg::PolygonOffset*>(attribute)){
((ive::PolygonOffset*)(attribute))->write(this);
}
else if(dynamic_cast<osg::ShadeModel*>(attribute)){
((ive::ShadeModel*)(attribute))->write(this);
}
else if(dynamic_cast<osg::Point*>(attribute)){
((ive::Point*)(attribute))->write(this);
}
// This is a Texture2D
else if(dynamic_cast<osg::Texture2D*>(attribute)){
((ive::Texture2D*)(attribute))->write(this);
}
// This is a TextureCubeMap
else if(dynamic_cast<osg::TextureCubeMap*>(attribute)){
((ive::TextureCubeMap*)(attribute))->write(this);
}
// This is a TexEnv
else if(dynamic_cast<osg::TexEnv*>(attribute)){
((ive::TexEnv*)(attribute))->write(this);
}
// This is a TexEnvCombine
else if(dynamic_cast<osg::TexEnvCombine*>(attribute)){
((ive::TexEnvCombine*)(attribute))->write(this);
}
// This is a TexGen
else if(dynamic_cast<osg::TexGen*>(attribute)){
((ive::TexGen*)(attribute))->write(this);
}
else{
std::string className = attribute->className();
throw Exception(std::string("StateSet::write(): Unknown StateAttribute: ").append(className));
}
}
}
void DataOutputStream::writeDrawable(osg::Drawable* drawable)
{
DrawableMap::iterator itr = _drawableMap.find(drawable);
if (itr!=_drawableMap.end())
{
// Id already exists so just write ID.
writeInt(itr->second);
}
else
{
// id doesn't exist so create a new ID and
// register the stateset.
int id = _drawableMap.size();
_drawableMap[drawable] = id;
// write the id.
writeInt(id);
if(dynamic_cast<osg::Geometry*>(drawable))
((ive::Geometry*)(drawable))->write(this);
else{
throw Exception("Unknown drawable in DataOutputStream::writeDrawable()");
}
}
}
void DataOutputStream::writeNode(osg::Node* node)
{
NodeMap::iterator itr = _nodeMap.find(node);
if (itr!=_nodeMap.end())
{
// Id already exists so just write ID.
writeInt(itr->second);
}
else
{
// id doesn't exist so create a new ID and
// register the stateset.
int id = _nodeMap.size();
_nodeMap[node] = id;
// write the id.
writeInt(id);
if(dynamic_cast<osg::MatrixTransform*>(node)){
((ive::MatrixTransform*)(node))->write(this);
}
// else if(dynamic_cast<osgfIVE::ViewPoint*>(node)){
// ((ive::ViewPoint*)(node))->write(this);
// }
else if(dynamic_cast<osg::PositionAttitudeTransform*>(node)){
((ive::PositionAttitudeTransform*)(node))->write(this);
}
else if(dynamic_cast<osg::LightSource*>(node)){
((ive::LightSource*)(node))->write(this);
}
else if(dynamic_cast<osg::Sequence*>(node)){
((ive::Sequence*)(node))->write(this);
}
else if(dynamic_cast<osg::Impostor*>(node)){
((ive::Impostor*)(node))->write(this);
}
else if(dynamic_cast<osg::LOD*>(node)){
((ive::LOD*)(node))->write(this);
}
else if(dynamic_cast<osg::Switch*>(node)){
((ive::Switch*)(node))->write(this);
}
else if(dynamic_cast<osg::OccluderNode*>(node)){
((ive::OccluderNode*)(node))->write(this);
}
else if(dynamic_cast<osg::Transform*>(node)){
((ive::Transform*)(node))->write(this);
}
else if(dynamic_cast<osg::Group*>(node)){
((ive::Group*)(node))->write(this);
}
else if(dynamic_cast<osg::Billboard*>(node)){
((ive::Billboard*)(node))->write(this);
}
else if(dynamic_cast<osg::Geode*>(node)){
((ive::Geode*)(node))->write(this);
}
else
throw Exception("Unknown node in Group::write()");
}
}

View File

@ -29,18 +29,18 @@ public:
void writeBool(bool b);
void writeChar(char c);
void writeUShort(unsigned short s);
void writeUInt(unsigned int s);
void writeInt(int i);
void writeFloat(float f);
void writeLong(long l);
void writeDouble(double d);
void writeString(std::string s);
void writeCharArray(char* data, int size);
void writeVec2(osg::Vec2 v);
void writeVec3(osg::Vec3 v);
void writeVec4(osg::Vec4 v);
void writeUByte4(osg::UByte4 v);
void writeQuat(osg::Quat q);
void writeStateSet(osg::StateSet* stateset);
void writeVec2(const osg::Vec2& v);
void writeVec3(const osg::Vec3& v);
void writeVec4(const osg::Vec4& v);
void writeUByte4(const osg::UByte4& v);
void writeQuat(const osg::Quat& q);
void writeBinding(osg::Geometry::AttributeBinding b);
void writeArray(osg::Array* a);
void writeIntArray(osg::IntArray* a);
@ -54,6 +54,11 @@ public:
void writeVec4Array(osg::Vec4Array* a);
void writeMatrix(osg::Matrix mat);
void writeStateSet(osg::StateSet* stateset);
void writeStateAttribute(osg::StateAttribute* sa);
void writeDrawable(osg::Drawable* sa);
void writeNode(osg::Node* sa);
// Set and get include image data in stream
void setIncludeImageData(bool b) {_includeImageData=b;};
bool getIncludeImageData() {return _includeImageData;};
@ -62,10 +67,17 @@ private:
std::ostream* _ostream;
// Container to map stateset uniques to their respective stateset.
typedef std::vector<int> StateSetList;
StateSetList _statesetList;
typedef std::map<osg::StateSet*,int> StateSetMap;
typedef std::map<osg::StateAttribute*,int> StateAttributeMap;
typedef std::map<osg::Drawable*,int> DrawableMap;
typedef std::map<osg::Node*,int> NodeMap;
StateSetMap _stateSetMap;
StateAttributeMap _stateAttributeMap;
DrawableMap _drawableMap;
NodeMap _nodeMap;
bool _includeImageData;
bool _includeImageData;
};

View File

@ -33,16 +33,23 @@ void Drawable::write(DataOutputStream* out){
// Write Drawable's properties.
// Write stateset.
out->writeInt((int)getStateSet());
if(getStateSet())
out->writeStateSet(getStateSet());
// Write stateset if any
if (getStateSet())
{
out->writeInt(1); //true we have a stateset
out->writeStateSet(getStateSet());
}
else
out->writeInt(0); //false we don't have a stateset
// Write shape
out->writeInt((int)getShape());
if (getShape()){
//static_cast<Shape*>(getShape())->write(out);
}
if (getShape())
{
out->writeInt(1); //true we have a shape
//static_cast<Shape*>(getShape())->write(out);
}
else
out->writeInt(0); //false we don't have a shape
// Write support display list.
out->writeBool(getSupportsDisplayList());

View File

@ -6,18 +6,22 @@ CXXFILES =\
AnimationPathCallback.cpp\
Billboard.cpp\
BlendFunc.cpp\
ConvexPlanarOccluder.cpp\
ConvexPlanarPolygon.cpp\
CullFace.cpp\
DataInputStream.cpp\
DataOutputStream.cpp\
DrawArrayLengths.cpp\
DrawArrays.cpp\
DrawElementsUShort.cpp\
DrawElementsUInt.cpp\
Drawable.cpp\
Exception.cpp\
Geode.cpp\
Geometry.cpp\
Group.cpp\
Image.cpp\
Impostor.cpp\
LOD.cpp\
Light.cpp\
LightSource.cpp\
@ -25,9 +29,14 @@ CXXFILES =\
MatrixTransform.cpp\
Node.cpp\
Object.cpp\
OccluderNode.cpp\
PositionAttitudeTransform.cpp\
PolygonOffset.cpp\
Point.cpp\
PrimitiveSet.cpp\
Sequence.cpp\
ShadeModel.cpp\
Switch.cpp\
StateSet.cpp\
TexEnv.cpp\
TexEnvCombine.cpp\

View File

@ -1,15 +1,15 @@
/**********************************************************************
*
* FILE: Geode.cpp
* FILE: Geode.cpp
*
* DESCRIPTION: Read/Write osg::Geode in binary format to disk.
* DESCRIPTION: Read/Write osg::Geode in binary format to disk.
*
* CREATED BY: Auto generated by iveGenerated
* and later modified by Rune Schmidt Jensen.
* CREATED BY: Auto generated by iveGenerated
* and later modified by Rune Schmidt Jensen.
*
* HISTORY: Created 18.3.2003
* HISTORY: Created 18.3.2003
*
* Copyright 2003 VR-C
* Copyright 2003 VR-C
**********************************************************************/
#include "Exception.h"
@ -23,64 +23,71 @@
using namespace ive;
void Geode::write(DataOutputStream* out){
// Write Geode's identification.
out->writeInt(IVEGEODE);
// If the osg class is inherited by any other class we should also write this to file.
osg::Node* node = dynamic_cast<osg::Node*>(this);
if(node){
((ive::Node*)(node))->write(out);
}
else
throw Exception("Geode::write(): Could not cast this osg::Geode to an osg::Node.");
// Write Geode's identification.
out->writeInt(IVEGEODE);
// If the osg class is inherited by any other class we should also write this to file.
osg::Node* node = dynamic_cast<osg::Node*>(this);
if(node){
((ive::Node*)(node))->write(out);
}
else
throw Exception("Geode::write(): Could not cast this osg::Geode to an osg::Node.");
// Write Geode's properties.
// Write Geode's properties.
// Write number of drawables.
out->writeInt(getNumDrawables());
// Write out every drawable.
for(unsigned int i=0;i<getNumDrawables();i++){
osg::Drawable* drawable = getDrawable(i);
if(dynamic_cast<osg::Geometry*>(drawable))
((ive::Geometry*)(drawable))->write(out);
else{
throw Exception("Unknown drawable in Geode::write()");
}
// Write number of drawables.
out->writeInt(getNumDrawables());
// Write out every drawable.
for(unsigned int i=0;i<getNumDrawables();i++){
osg::Drawable* drawable = getDrawable(i);
#if 0
if(dynamic_cast<osg::Geometry*>(drawable))
((ive::Geometry*)(drawable))->write(out);
else{
throw Exception("Unknown drawable in Geode::write()");
}
#else
out->writeDrawable(drawable);
#endif
}
}
void Geode::read(DataInputStream* in){
// Read Geode's identification.
int id = in->peekInt();
if(id == IVEGEODE){
// Code to read Geode's properties.
id = in->readInt();
// If the osg class is inherited by any other class we should also read this from file.
osg::Node* node = dynamic_cast<osg::Node*>(this);
if(node){
((ive::Node*)(node))->read(in);
}
else
throw Exception("Geode::read(): Could not cast this osg::Geode to an osg::Node.");
// Read Geode's identification.
int id = in->peekInt();
if(id == IVEGEODE){
// Code to read Geode's properties.
id = in->readInt();
// If the osg class is inherited by any other class we should also read this from file.
osg::Node* node = dynamic_cast<osg::Node*>(this);
if(node){
((ive::Node*)(node))->read(in);
}
else
throw Exception("Geode::read(): Could not cast this osg::Geode to an osg::Node.");
// Read number of drawables.
int size = in->readInt();
// Read the drawables.
for(int i = 0; i<size; i++){
int id = in->peekInt();
osg::Drawable* drawable;
if(id == IVEGEOMETRY){
drawable = new osg::Geometry();
((Geometry*)(drawable))->read(in);
addDrawable(drawable);
}
else
throw Exception("Unknown drawable identification in Geode::read()");
}
}
else{
throw Exception("Geode::read(): Expected Geode identification.");
}
// Read number of drawables.
int size = in->readInt();
// Read the drawables.
for(int i = 0; i<size; i++){
#if 0
int id = in->peekInt();
osg::Drawable* drawable;
if(id == IVEGEOMETRY){
drawable = new osg::Geometry();
((Geometry*)(drawable))->read(in);
addDrawable(drawable);
}
else
throw Exception("Unknown drawable identification in Geode::read()");
#else
addDrawable(in->readDrawable());
#endif
}
}
else{
throw Exception("Geode::read(): Expected Geode identification.");
}
}

View File

@ -18,6 +18,7 @@
#include "DrawArrays.h"
#include "DrawArrayLengths.h"
#include "DrawElementsUShort.h"
#include "DrawElementsUInt.h"
using namespace ive;
@ -46,61 +47,64 @@ void Geometry::write(DataOutputStream* out){
((ive::DrawArrayLengths*)(getPrimitiveSet(i)))->write(out);
else if(dynamic_cast<osg::DrawElementsUShort*>(getPrimitiveSet(i)))
((ive::DrawElementsUShort*)(getPrimitiveSet(i)))->write(out);
else if(dynamic_cast<osg::DrawElementsUInt*>(getPrimitiveSet(i)))
((ive::DrawElementsUInt*)(getPrimitiveSet(i)))->write(out);
else
throw Exception("Unknown PrimitivSet in Geometry::write()");
}
// Write vertex array if any
out->writeInt((int)getVertexArray());
if (getVertexArray()){
out->writeVec3Array(getVertexArray());
out->writeLong((long)getVertexArray());
if (getVertexArray())
{
out->writeArray(getVertexArray());
}
// Write vertex indices if any
out->writeInt((int)getVertexIndices());
out->writeLong((long)getVertexIndices());
if (getVertexIndices()){
out->writeArray(getVertexIndices());
}
// Write normal array if any
out->writeInt((int)getNormalArray());
out->writeLong((long)getNormalArray());
if (getNormalArray()){
out->writeBinding(getNormalBinding());
out->writeVec3Array(getNormalArray());
}
// Write normal indices if any
out->writeInt((int)getNormalIndices());
out->writeLong((long)getNormalIndices());
if (getNormalIndices()){
out->writeArray(getNormalIndices());
}
// Write color array if any.
out->writeInt((int)getColorArray());
out->writeLong((long)getColorArray());
if (getColorArray()){
out->writeBinding(getColorBinding());
out->writeArray(getColorArray());
}
// Write color indices if any
out->writeInt((int)getColorIndices());
out->writeLong((long)getColorIndices());
if (getColorIndices()){
out->writeArray(getColorIndices());
}
// Write secondary color array if any
out->writeInt((int)getSecondaryColorArray());
out->writeLong((long)getSecondaryColorArray());
if (getSecondaryColorArray()){
out->writeBinding(getSecondaryColorBinding());
out->writeArray(getSecondaryColorArray());
}
// Write second color indices if any
out->writeInt((int)getSecondaryColorIndices());
out->writeLong((long)getSecondaryColorIndices());
if (getSecondaryColorIndices()){
out->writeArray(getSecondaryColorIndices());
}
// Write fog coord array if any
out->writeInt((int)getFogCoordArray());
out->writeLong((long)getFogCoordArray());
if (getFogCoordArray()){
out->writeBinding(getFogCoordBinding());
out->writeArray(getFogCoordArray());
}
// Write fog coord indices if any
out->writeInt((int)getFogCoordIndices());
out->writeLong((long)getFogCoordIndices());
if (getFogCoordIndices()){
out->writeArray(getFogCoordIndices());
}
@ -159,6 +163,11 @@ void Geometry::read(DataInputStream* in){
((ive::DrawElementsUShort*)(prim))->read(in);
addPrimitiveSet(prim);
}
else if(primID==IVEDRAWELEMENTSUINT){
prim = new osg::DrawElementsUInt();
((ive::DrawElementsUInt*)(prim))->read(in);
addPrimitiveSet(prim);
}
else{
throw Exception("Unkown PrimitiveSet in Geometry::read()");
}
@ -167,7 +176,7 @@ void Geometry::read(DataInputStream* in){
// Read vertex array if any
int va=in->readInt();
if (va){
setVertexArray(in->readVec3Array());
setVertexArray(in->readArray());
}
// Read vertex indices if any
int vi = in->readInt();

View File

@ -1,15 +1,15 @@
/**********************************************************************
*
* FILE: Group.cpp
* FILE: Group.cpp
*
* DESCRIPTION: Read/Write osg::Group in binary format to disk.
* DESCRIPTION: Read/Write osg::Group in binary format to disk.
*
* CREATED BY: Auto generated by iveGenerated
* and later modified by Rune Schmidt Jensen.
* CREATED BY: Auto generated by iveGenerated
* and later modified by Rune Schmidt Jensen.
*
* HISTORY: Created 17.3.2003
* HISTORY: Created 17.3.2003
*
* Copyright 2003 VR-C
* Copyright 2003 VR-C
**********************************************************************/
#include "Exception.h"
@ -28,138 +28,54 @@
using namespace ive;
void Group::write(DataOutputStream* out){
// Write Group's identification.
out->writeInt(IVEGROUP);
// If the osg class is inherited by any other class we should also write this to file.
osg::Node* node = dynamic_cast<osg::Node*>(this);
if(node){
static_cast<ive::Node*>(node)->write(out);
}
else
throw Exception("Group::write(): Could not cast this osg::Group to an osg::Node.");
// Write Group's identification.
out->writeInt(IVEGROUP);
// If the osg class is inherited by any other class we should also write this to file.
osg::Node* node = dynamic_cast<osg::Node*>(this);
if(node){
static_cast<ive::Node*>(node)->write(out);
}
else
throw Exception("Group::write(): Could not cast this osg::Group to an osg::Node.");
// Write Group's properties.
// Write Group's properties.
// Write number of children.
out->writeInt(getNumChildren());
// Write children.
// Write number of children.
out->writeInt(getNumChildren());
// Write children.
for(unsigned int i=0; i<getNumChildren(); i++){
osg::Node* child = getChild(i);
if(dynamic_cast<osg::MatrixTransform*>(child)){
((ive::MatrixTransform*)(child))->write(out);
}
// else if(dynamic_cast<osgfIVE::ViewPoint*>(child)){
// ((ive::ViewPoint*)(child))->write(out);
// }
else if(dynamic_cast<osg::PositionAttitudeTransform*>(child)){
((ive::PositionAttitudeTransform*)(child))->write(out);
}
else if(dynamic_cast<osg::LightSource*>(child)){
((ive::LightSource*)(child))->write(out);
}
else if(dynamic_cast<osg::Sequence*>(child)){
((ive::Sequence*)(child))->write(out);
}
else if(dynamic_cast<osg::LOD*>(child)){
((ive::LOD*)(child))->write(out);
}
else if(dynamic_cast<osg::Transform*>(child)){
((ive::Transform*)(child))->write(out);
}
else if(dynamic_cast<osg::Group*>(child)){
((ive::Group*)(child))->write(out);
}
else if(dynamic_cast<osg::Billboard*>(child)){
((ive::Billboard*)(child))->write(out);
}
else if(dynamic_cast<osg::Geode*>(child)){
((ive::Geode*)(child))->write(out);
}
else
throw Exception("Unknown child in Group::write()");
osg::Node* child = getChild(i);
out->writeNode(child);
}
}
void Group::read(DataInputStream* in){
// Read Group's identification.
int id = in->peekInt();
if(id == IVEGROUP){
// Read Group's identification.
id = in->readInt();
// Read Group's identification.
int id = in->peekInt();
if(id == IVEGROUP){
// Read Group's identification.
id = in->readInt();
// If the osg class is inherited by any other class we should also read this from file.
osg::Node* node = dynamic_cast<osg::Node*>(this);
if(node){
((ive::Node*)(node))->read(in);
}
else
throw Exception("Group::read(): Could not cast this osg::Group to an osg::Node.");
// If the osg class is inherited by any other class we should also read this from file.
osg::Node* node = dynamic_cast<osg::Node*>(this);
if(node){
((ive::Node*)(node))->read(in);
}
else
throw Exception("Group::read(): Could not cast this osg::Group to an osg::Node.");
// Read groups properties.
// Read groups properties.
// Read number of children.
int size = in->readInt();
// Read children.
for(int i=0; i<size; i++){
int id = in->peekInt();
osg::Node* child;
if(id == IVEMATRIXTRANSFORM){
child = new osg::MatrixTransform();
((ive::MatrixTransform*)(child))->read(in);
addChild(child);
}
// else if(id == IVEVIEWPOINT){
// child = new osgfIVE::ViewPoint();
// ((ive::ViewPoint*)(child))->read(in);
// addChild(child);
// }
else if(id == IVEPOSITIONATTITUDETRANSFORM){
child = new osg::PositionAttitudeTransform();
((ive::PositionAttitudeTransform*)(child))->read(in);
addChild(child);
}
else if(id == IVELIGHTSOURCE){
child = new osg::LightSource();
((ive::LightSource*)(child))->read(in);
addChild(child);
}
else if(id == IVESEQUENCE){
child = new osg::Sequence();
((ive::Sequence*)(child))->read(in);
addChild(child);
}
else if(id == IVELOD){
child = new osg::LOD();
((ive::LOD*)(child))->read(in);
addChild(child);
}
else if(id == IVETRANSFORM){
child = new osg::Transform();
((ive::Transform*)(child))->read(in);
addChild(child);
}
else if(id == IVEGROUP){
child = new osg::Group();
((ive::Group*)(child))->read(in);
addChild(child);
}
else if(id == IVEBILLBOARD){
child = new osg::Billboard();
((ive::Billboard*)(child))->read(in);
addChild(child);
}
else if(id == IVEGEODE){
child = new osg::Geode();
((ive::Geode*)(child))->read(in);
addChild(child);
}
else{
throw Exception("Unknown child identification in Group::read()");
}
}
}
else{
throw Exception("Group::read(): Expected Group identification");
}
// Read number of children.
int size = in->readInt();
// Read children.
for(int i=0; i<size; i++)
{
addChild(in->readNode());
}
}
else{
throw Exception("Group::read(): Expected Group identification");
}
}

View File

@ -1,15 +1,15 @@
/**********************************************************************
*
* FILE: Image.cpp
* FILE: Image.cpp
*
* DESCRIPTION: Read/Write osg::Image in binary format to disk.
* DESCRIPTION: Read/Write osg::Image in binary format to disk.
*
* CREATED BY: Auto generated by iveGenerated
* and later modified by Rune Schmidt Jensen.
* CREATED BY: Auto generated by iveGenerated
* and later modified by Rune Schmidt Jensen.
*
* HISTORY: Created 20.3.2003
* HISTORY: Created 20.3.2003
*
* Copyright 2003 VR-C
* Copyright 2003 VR-C
**********************************************************************/
#include "Exception.h"
@ -18,104 +18,125 @@
using namespace ive;
void Image::write(DataOutputStream* out){
// Write Image's identification.
out->writeInt(IVEIMAGE);
// If the osg class is inherited by any other class we should also write this to file.
osg::Object* obj = dynamic_cast<osg::Object*>(this);
if(obj){
((ive::Object*)(obj))->write(out);
}
else
throw Exception("Image::write(): Could not cast this osg::Image to an osg::Object.");
// Write Image's properties.
void Image::write(DataOutputStream* out)
{
// Write Image's identification.
out->writeInt(IVEIMAGE);
// If the osg class is inherited by any other class we should also write this to file.
osg::Object* obj = dynamic_cast<osg::Object*>(this);
if(obj){
((ive::Object*)(obj))->write(out);
}
else
throw Exception("Image::write(): Could not cast this osg::Image to an osg::Object.");
// Write Image's properties.
// Write name
out->writeString(getFileName());
// Write name
out->writeString(getFileName());
// Write width, height, depth of image.
out->writeInt(s());
out->writeInt(t());
out->writeInt(r());
// Write width, height, depth of image.
out->writeInt(s());
out->writeInt(t());
out->writeInt(r());
std::cout << getFileName()<<"\t"<<s()<<"\t"<<t()<<std::endl;
// Write formats, type and packing
// Write formats, type and packing
out->writeInt(getInternalTextureFormat());
out->writeInt(getPixelFormat());
out->writeInt(getDataType());
out->writeInt(getPacking());
out->writeInt(getPixelFormat());
out->writeInt(getDataType());
out->writeInt(getPacking());
// Write modified tag.
out->writeInt(getModifiedTag());
// Write modified tag.
out->writeInt(getModifiedTag());
// Write mipmapdata vector
int size = _mipmapData.size();
out->writeInt(size);
for(int i=0;i<size;i++)
out->writeInt(_mipmapData[i]);
// Write mipmapdata vector
int size = _mipmapData.size();
out->writeInt(size);
for(int i=0;i<size;i++)
out->writeInt(_mipmapData[i]);
// Write image data if any
out->writeInt((int)data());
if(data()){
// Compute the size of image data and write this.
unsigned int size = computeRowWidthInBytes(s(),getPixelFormat(),getDataType(),getPacking())*t()*r();
out->writeInt(size);
// Write the data
out->writeCharArray((char*)data(), size);
}
// Write image data if any
out->writeLong((long)data());
if(data()){
// Compute the size of image data and write this.
unsigned int size = getTotalSizeInBytesIncludingMipmaps();
out->writeInt(size);
// Write the data
out->writeCharArray((char*)data(), size);
}
}
void Image::read(DataInputStream* in){
// Peek Image's identification.
int id = in->peekInt();
if(id == IVEIMAGE){
// Read Image's identification.
id = in->readInt();
// If the osg class is inherited by any other class we should also read this from file.
osg::Object* obj = dynamic_cast<osg::Object*>(this);
if(obj){
((ive::Object*)(obj))->read(in);
}
else
throw Exception("Image::read(): Could not cast this osg::Image to an osg::Object.");
// Read Image's properties.
void Image::read(DataInputStream* in)
{
// Peek Image's identification.
int id = in->peekInt();
if(id == IVEIMAGE){
// Read Image's identification.
id = in->readInt();
// If the osg class is inherited by any other class we should also read this from file.
osg::Object* obj = dynamic_cast<osg::Object*>(this);
if(obj){
((ive::Object*)(obj))->read(in);
}
else
throw Exception("Image::read(): Could not cast this osg::Image to an osg::Object.");
// Read Image's properties.
// Read name
setFileName(in->readString());
// Read name
setFileName(in->readString());
// Read width, height, depth of image.
int s=in->readInt();
int t=in->readInt();
int r=in->readInt();
// Read width, height, depth of image.
int is=in->readInt();
int it=in->readInt();
int ir=in->readInt();
// Read formats, type and packing
// Read formats, type and packing
GLint internalTextureFormat = (GLint) in->readInt();
GLenum pixelFormat = (GLenum) in->readInt();
GLenum pixelFormat = (GLenum) in->readInt();
GLenum dataType = (GLenum) in->readInt();;
unsigned int packing = (unsigned int)in->readInt();
// Read modified tag.
// Read modified tag.
setModifiedTag((unsigned int)in->readInt());
// Read mipmapdata vector
int size = in->readInt();
_mipmapData.resize(size);
for(int i=0;i<size;i++)
_mipmapData[i]=(unsigned int)in->readInt();
// Read mipmapdata vector
int size = in->readInt();
_mipmapData.resize(size);
// Read image data if any
if(in->readInt()){
unsigned int dataSize = (unsigned int)in->readInt();
//char* data = (char*)malloc (dataSize);
char* data = new char[dataSize];
if(!data)
throw Exception("Image::read(): Unable to allocate memory for image data.");
in->readCharArray(data,dataSize);
setImage(s, t, r, internalTextureFormat, pixelFormat,
dataType, (unsigned char* ) data, osg::Image::USE_NEW_DELETE, packing);
}
}
else{
throw Exception("Image::read(): Expected Image identification.");
}
//if (size) std::cout<<"is mip mapped ";
for(int i=0;i<size;i++)
{
_mipmapData[i]=(unsigned int)in->readInt();
//std::cout<<_mipmapData[i]<<"\t";
}
//std::cout<<std::endl;
// Read image data if any
if(in->readInt()){
unsigned int dataSize = (unsigned int)in->readInt();
//static int totalSize = 0;
//totalSize += dataSize;
//std::cout<<getFileName()<<" "<<is<<" "<<it<<std::endl;
//std::cout<<" dataSize = "<<dataSize<<"\tTotalSize = "<<totalSize<<std::endl;
//char* data = (char*)malloc (dataSize);
char* data = new char[dataSize];
if(!data)
throw Exception("Image::read(): Unable to allocate memory for image data.");
in->readCharArray(data,dataSize);
setImage(is, it, ir, internalTextureFormat, pixelFormat,
dataType, (unsigned char* ) data, osg::Image::USE_NEW_DELETE, packing);
}
}
else{
throw Exception("Image::read(): Expected Image identification.");
}
}

View File

@ -32,7 +32,7 @@ void LightSource::write(DataOutputStream* out){
// Write LightSource's properties.
// Write out light
out->writeInt((int)getLight());
out->writeLong((long)getLight());
if(getLight()){
((ive::Light*)(getLight()))->write(out);
}

View File

@ -51,7 +51,7 @@ void Node::write(DataOutputStream* out){
out->writeString(desc[i]);
}
// Write Stateset if any
out->writeInt((int) getStateSet());
out->writeLong((long) getStateSet());
if(getStateSet())
out->writeStateSet(getStateSet());
@ -59,7 +59,7 @@ void Node::write(DataOutputStream* out){
// Write UpdateCallback if any
osg::NodeCallback* nc = getUpdateCallback();
if(nc && dynamic_cast<osg::AnimationPathCallback*>(nc)){
out->writeInt((int)nc);
out->writeLong((long)nc);
((ive::AnimationPathCallback*)(nc))->write(out);
}
else
@ -103,4 +103,4 @@ void Node::read(DataInputStream* in){
else{
throw Exception("Node::read(): Expected Node identification");
}
}
}

View File

@ -2,64 +2,73 @@
#define IVE_READWRITE 1
#include "DataInputStream.h"
#include "DataOutputStream.h"
#include "DataOutputStream.h"
namespace ive {
// Objects and Nodes
#define IVEOBJECT 0x00000001
#define IVENODE 0x00000002
#define IVEGROUP 0x00000003
#define IVEMATRIXTRANSFORM 0x00000004
#define IVESTATESET 0x00000005
#define IVEGEODE 0x00000006
#define IVEIMAGE 0x00000007
#define IVELIGHTSOURCE 0x00000008
#define IVELIGHT 0x00000009
#define IVEBILLBOARD 0x00000010
#define IVELOD 0x00000011
#define IVESEQUENCE 0x00000012
#define IVETRANSFORM 0x00000013
#define IVEPOSITIONATTITUDETRANSFORM 0x00000014
#define IVEANIMATIONPATH 0x00000015
#define IVEOBJECT 0x00000001
#define IVENODE 0x00000002
#define IVEGROUP 0x00000003
#define IVEMATRIXTRANSFORM 0x00000004
#define IVESTATESET 0x00000005
#define IVEGEODE 0x00000006
#define IVEIMAGE 0x00000007
#define IVELIGHTSOURCE 0x00000008
#define IVELIGHT 0x00000009
#define IVEBILLBOARD 0x00000010
#define IVELOD 0x00000011
#define IVESEQUENCE 0x00000012
#define IVETRANSFORM 0x00000013
#define IVEPOSITIONATTITUDETRANSFORM 0x00000014
#define IVEANIMATIONPATH 0x00000015
#define IVESWITCH 0x00000016
#define IVEOCCLUDERNODE 0x00000017
#define IVEIMPOSTOR 0x00000018
#define IVECONVEXPLANAROCCLUDER 0x00000019
#define IVECONVEXPLANARPOLYGON 0x00000020
// Node callbacks
#define IVENODECALLBACK 0x00000050
#define IVEANIMATIONPATHCALLBACK 0x00000051
#define IVENODECALLBACK 0x00000050
#define IVEANIMATIONPATHCALLBACK 0x00000051
// State attributes.
#define IVESTATEATTRIBUTE 0x00000100
#define IVEALPHAFUNC 0x00000101
#define IVEBLENDFUNC 0x00000102
#define IVEMATERIAL 0x00000110
#define IVETEXTURE 0x00000120
#define IVETEXTURE1D 0x00000121
#define IVETEXTURE2D 0x00000122
#define IVETEXTURE3D 0x00000123
#define IVETEXTURECUBEMAP 0x00000124
#define IVETEXENV 0x00000125
#define IVETEXENVCOMBINE 0x00000126
#define IVETEXGEN 0x00000127
#define IVECULLFACE 0x00000128
#define IVESTATEATTRIBUTE 0x00000100
#define IVEALPHAFUNC 0x00000101
#define IVEBLENDFUNC 0x00000102
#define IVEMATERIAL 0x00000110
#define IVETEXTURE 0x00000120
#define IVETEXTURE1D 0x00000121
#define IVETEXTURE2D 0x00000122
#define IVETEXTURE3D 0x00000123
#define IVETEXTURECUBEMAP 0x00000124
#define IVETEXENV 0x00000125
#define IVETEXENVCOMBINE 0x00000126
#define IVETEXGEN 0x00000127
#define IVECULLFACE 0x00000128
#define IVEPOLYGONOFFSET 0x00000129
#define IVESHADEMODEL 0x0000012A
#define IVEPOINT 0x0000012B
// Drawables
#define IVEDRAWABLE 0x00001000
#define IVEGEOMETRY 0x00001001
#define IVEDRAWABLE 0x00001000
#define IVEGEOMETRY 0x00001001
// Primitive set
#define IVEPRIMITIVESET 0x00010000
#define IVEDRAWARRAYS 0x00010001
#define IVEDRAWARRAYLENGTHS 0x00010002
#define IVEDRAWELEMENTSUSHORT 0x00010003
#define IVEPRIMITIVESET 0x00010000
#define IVEDRAWARRAYS 0x00010001
#define IVEDRAWARRAYLENGTHS 0x00010002
#define IVEDRAWELEMENTSUSHORT 0x00010003
#define IVEDRAWELEMENTSUINT 0x00010004
// Our own classes
#define IVEVIEWPOINT 0x00100001
#define IVEVIEWPOINT 0x00100001
class ReadWrite{
public:
virtual void write(DataOutputStream* out) const = 0;
virtual void read(DataInputStream* out) const = 0;
virtual void write(DataOutputStream* out) const = 0;
virtual void read(DataInputStream* out) const = 0;
};
}

View File

@ -32,26 +32,9 @@ class IVEReaderWriter : public ReaderWriter
{
try{
// Create datainputstream.
ive::DataInputStream* in = new ive::DataInputStream(&fin);
ive::DataInputStream in(&fin);
// Which object is written first in the stream.
int id = in->peekInt();
if(id==IVEMATRIXTRANSFORM)
{
osg::MatrixTransform* rootNode = new osg::MatrixTransform;
((ive::MatrixTransform*)(rootNode))->read(in);
return rootNode;
}
else if(id==IVEGROUP)
{
osg::Group* rootNode = new osg::Group;
((ive::Group*)(rootNode))->read(in);
return rootNode;
}
else{
std::cout <<"Unknown class identification in file "<< id << std::endl;
}
return in.readNode();
}
catch(ive::Exception e)
{
@ -63,6 +46,9 @@ class IVEReaderWriter : public ReaderWriter
virtual WriteResult writeNode(const Node& node,const std::string& fileName, const osgDB::ReaderWriter::Options* options)
{
std::string ext = getFileExtension(fileName);
if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED;
std::ofstream fout(fileName.c_str(), std::ios::out | std::ios::binary);
WriteResult result = writeNode(node, fout, options);
fout.close();
@ -73,15 +59,9 @@ class IVEReaderWriter : public ReaderWriter
{
try
{
ive::DataOutputStream* out = new ive::DataOutputStream(&fout);
// write ive file.
if(dynamic_cast<const osg::MatrixTransform*>(&node))
const_cast<ive::MatrixTransform*>(static_cast<const ive::MatrixTransform*>(&node))->write(out);
else if(dynamic_cast<const osg::Group*>(&node))
const_cast<ive::Group*>(static_cast<const ive::Group*>(&node))->write(out);
else
std::cout<<"File must start with a MatrixTransform or Group "<<std::endl;
fout.flush();
ive::DataOutputStream out(&fout);
out.writeNode(const_cast<osg::Node*>(&node));
return WriteResult::FILE_SAVED;
}
catch(ive::Exception e)

View File

@ -1,15 +1,15 @@
/**********************************************************************
*
* FILE: StateSet.cpp
* FILE: StateSet.cpp
*
* DESCRIPTION: Read/Write osg::StateSet in binary format to disk.
* DESCRIPTION: Read/Write osg::StateSet in binary format to disk.
*
* CREATED BY: Auto generated by iveGenerated
* and later modified by Rune Schmidt Jensen.
* CREATED BY: Auto generated by iveGenerated
* and later modified by Rune Schmidt Jensen.
*
* HISTORY: Created 17.3.2003
* HISTORY: Created 17.3.2003
*
* Copyright 2003 VR-C
* Copyright 2003 VR-C
**********************************************************************/
#include "Exception.h"
@ -18,6 +18,8 @@
#include "BlendFunc.h"
#include "Material.h"
#include "CullFace.h"
#include "PolygonOffset.h"
#include "ShadeModel.h"
#include "Texture2D.h"
#include "TextureCubeMap.h"
#include "TexEnv.h"
@ -29,238 +31,148 @@
using namespace ive;
void StateSet::write(DataOutputStream* out){
// Write StateSet's identification.
out->writeInt(IVESTATESET);
// If the osg class is inherited by any other class we should also write this to file.
osg::Object* obj = dynamic_cast<osg::Object*>(this);
if(obj){
((ive::Object*)(obj))->write(out);
}
else
throw Exception("StateSet::write(): Could not cast this osg::StateSet to an osg::Object.");
// Write StateSet's identification.
out->writeInt(IVESTATESET);
// If the osg class is inherited by any other class we should also write this to file.
osg::Object* obj = dynamic_cast<osg::Object*>(this);
if(obj){
((ive::Object*)(obj))->write(out);
}
else
throw Exception("StateSet::write(): Could not cast this osg::StateSet to an osg::Object.");
// Write render bin bin details.
switch(getRenderBinMode()){
case osg::StateSet::INHERIT_RENDERBIN_DETAILS: out->writeChar((char)0);break;
case osg::StateSet::USE_RENDERBIN_DETAILS: out->writeChar((char)1);break;
case osg::StateSet::OVERRIDE_RENDERBIN_DETAILS: out->writeChar((char)2);break;
case osg::StateSet::ENCLOSE_RENDERBIN_DETAILS: out->writeChar((char)3);break;
default: throw Exception("Unknown RenderBinMode in StateSet::write()");
}
out->writeInt(getBinNumber());
out->writeString(getBinName());
// Write render bin bin details.
switch(getRenderBinMode()){
case osg::StateSet::INHERIT_RENDERBIN_DETAILS: out->writeChar((char)0);break;
case osg::StateSet::USE_RENDERBIN_DETAILS: out->writeChar((char)1);break;
case osg::StateSet::OVERRIDE_RENDERBIN_DETAILS: out->writeChar((char)2);break;
case osg::StateSet::ENCLOSE_RENDERBIN_DETAILS: out->writeChar((char)3);break;
default: throw Exception("Unknown RenderBinMode in StateSet::write()");
}
out->writeInt(getBinNumber());
out->writeString(getBinName());
StateSet::ModeList ml = getModeList();
StateSet::AttributeList al = getAttributeList();
StateSet::ModeList ml = getModeList();
StateSet::AttributeList al = getAttributeList();
// Write stateset modes, this could for instance be GL_NORMALIZE, GL_LIGHT, etc.
out->writeInt(ml.size());
for(StateSet::ModeList::const_iterator mitr=ml.begin(); mitr!=ml.end(); ++mitr){
out->writeInt((unsigned int)mitr->first);
out->writeInt((unsigned int)mitr->second);
}
// Write stateset modes, this could for instance be GL_NORMALIZE, GL_LIGHT, etc.
out->writeInt(ml.size());
for(StateSet::ModeList::const_iterator mitr=ml.begin(); mitr!=ml.end(); ++mitr){
out->writeInt((unsigned int)mitr->first);
out->writeInt((unsigned int)mitr->second);
}
// Write stateset attributes, this could for instance be alphafunctions, materials, etc.
out->writeInt(al.size());
for(StateSet::AttributeList::iterator aitr=al.begin(); aitr!=al.end(); ++aitr){
// This is a BlendFunc.
if(dynamic_cast<osg::BlendFunc*>(aitr->second.first.get())){
((ive::BlendFunc*)(aitr->second.first.get()))->write(out);
out->writeInt(aitr->second.second);
}
// This is a Material
else if(dynamic_cast<osg::Material*>(aitr->second.first.get())){
((ive::Material*)(aitr->second.first.get()))->write(out);
out->writeInt(aitr->second.second);
}
// This is a CullFace
else if(dynamic_cast<osg::CullFace*>(aitr->second.first.get())){
((ive::CullFace*)(aitr->second.first.get()))->write(out);
out->writeInt(aitr->second.second);
}
else{
std::string className = (aitr->second.first.get())->className();
throw Exception(std::string("StateSet::write(): Unknown StateAttribute: ").append(className));
}
}
// Write stateset attributes, this could for instance be alphafunctions, materials, etc.
out->writeInt(al.size());
for(StateSet::AttributeList::iterator aitr=al.begin(); aitr!=al.end(); ++aitr){
out->writeStateAttribute(aitr->second.first.get());
out->writeInt(aitr->second.second);
}
StateSet::TextureModeList tml = getTextureModeList();
StateSet::TextureAttributeList tal = getTextureAttributeList();
StateSet::TextureModeList tml = getTextureModeList();
StateSet::TextureAttributeList tal = getTextureAttributeList();
// Write texture stateset modes, this could for instance be TEXGEN ON, TEXTURECUBEMAP ON, etc.
int nUnits = tml.size();
out->writeInt(nUnits);
// Write texture stateset modes, this could for instance be TEXGEN ON, TEXTURECUBEMAP ON, etc.
int nUnits = tml.size();
out->writeInt(nUnits);
int unit;
for(unit=0;unit<nUnits;unit++){
ml = tml[unit];
out->writeInt(ml.size());
for(StateSet::ModeList::const_iterator mitr=ml.begin(); mitr!=ml.end(); ++mitr){
out->writeInt((unsigned int)mitr->first);
out->writeInt((unsigned int)mitr->second);
}
}
for(unit=0;unit<nUnits;unit++){
ml = tml[unit];
out->writeInt(ml.size());
for(StateSet::ModeList::const_iterator mitr=ml.begin(); mitr!=ml.end(); ++mitr){
out->writeInt((unsigned int)mitr->first);
out->writeInt((unsigned int)mitr->second);
}
}
// Write texture attributes, this could for instance texture2D, texturecubemap
nUnits = tal.size();
out->writeInt(nUnits);
for(unit=0;unit<nUnits;unit++){
al = tal[unit];
out->writeInt(al.size());
for(StateSet::AttributeList::iterator aitr=al.begin(); aitr!=al.end(); ++aitr){
// This is a Texture2D
if(dynamic_cast<osg::Texture2D*>(aitr->second.first.get())){
((ive::Texture2D*)(aitr->second.first.get()))->write(out);
out->writeInt(aitr->second.second);
}
// This is a TextureCubeMap
else if(dynamic_cast<osg::TextureCubeMap*>(aitr->second.first.get())){
((ive::TextureCubeMap*)(aitr->second.first.get()))->write(out);
out->writeInt(aitr->second.second);
}
// This is a TexEnv
else if(dynamic_cast<osg::TexEnv*>(aitr->second.first.get())){
((ive::TexEnv*)(aitr->second.first.get()))->write(out);
out->writeInt(aitr->second.second);
}
// This is a TexEnvCombine
else if(dynamic_cast<osg::TexEnvCombine*>(aitr->second.first.get())){
((ive::TexEnvCombine*)(aitr->second.first.get()))->write(out);
out->writeInt(aitr->second.second);
}
// This is a TexGen
else if(dynamic_cast<osg::TexGen*>(aitr->second.first.get())){
((ive::TexGen*)(aitr->second.first.get()))->write(out);
out->writeInt(aitr->second.second);
}
else{
std::string className = (aitr->second.first.get())->className();
throw Exception(std::string("StateSet::write(): Unknown Texture StateAttribute: ").append(className));
}
}
}
// Write texture attributes, this could for instance texture2D, texturecubemap
nUnits = tal.size();
out->writeInt(nUnits);
for(unit=0;unit<nUnits;unit++){
al = tal[unit];
out->writeInt(al.size());
for(StateSet::AttributeList::iterator aitr=al.begin(); aitr!=al.end(); ++aitr){
out->writeStateAttribute(aitr->second.first.get());
out->writeInt(aitr->second.second);
}
}
}
void StateSet::read(DataInputStream* in){
// Read StateSet's identification.
int id = in->peekInt();
if(id == IVESTATESET){
// Code to read StateSet's properties.
id = in->readInt();
// If the osg class is inherited by any other class we should also read this from file.
osg::Object* obj = dynamic_cast<osg::Object*>(this);
if(obj){
((ive::Object*)(obj))->read(in);;
}
else
throw Exception("StateSet::read(): Could not cast this osg::StateSet to an osg::Object.");
// Read StateSet's identification.
int id = in->peekInt();
if(id == IVESTATESET){
// Code to read StateSet's properties.
id = in->readInt();
// If the osg class is inherited by any other class we should also read this from file.
osg::Object* obj = dynamic_cast<osg::Object*>(this);
if(obj){
((ive::Object*)(obj))->read(in);;
}
else
throw Exception("StateSet::read(): Could not cast this osg::StateSet to an osg::Object.");
// Read render bin details.
char c = in->readChar();
int num = in->readInt();
std::string name = in->readString();
switch((int)c){
case 0:
setRenderBinDetails(num, name, osg::StateSet::INHERIT_RENDERBIN_DETAILS);
break;
case 1:
setRenderBinDetails(num, name, osg::StateSet::USE_RENDERBIN_DETAILS);
break;
case 2:
setRenderBinDetails(num, name, osg::StateSet::OVERRIDE_RENDERBIN_DETAILS);
break;
case 3:
setRenderBinDetails(num, name, osg::StateSet::ENCLOSE_RENDERBIN_DETAILS);
break;
default: throw Exception("Unkown RenderBinMode in StateSet::read()");
}
// Read render bin details.
char c = in->readChar();
int num = in->readInt();
std::string name = in->readString();
switch((int)c){
case 0:
setRenderBinDetails(num, name, osg::StateSet::INHERIT_RENDERBIN_DETAILS);
break;
case 1:
setRenderBinDetails(num, name, osg::StateSet::USE_RENDERBIN_DETAILS);
break;
case 2:
setRenderBinDetails(num, name, osg::StateSet::OVERRIDE_RENDERBIN_DETAILS);
break;
case 3:
setRenderBinDetails(num, name, osg::StateSet::ENCLOSE_RENDERBIN_DETAILS);
break;
default: throw Exception("Unkown RenderBinMode in StateSet::read()");
}
// Read stateset modes.
int size = in->readInt();
// Read stateset modes.
int size = in->readInt();
int i;
for(i=0;i<size;i++){
int mode = in->readInt();
int value = in->readInt();
setMode((osg::StateAttribute::GLMode)mode, (osg::StateAttribute::GLModeValue)value);
}
for(i=0;i<size;i++){
int mode = in->readInt();
int value = in->readInt();
setMode((osg::StateAttribute::GLMode)mode, (osg::StateAttribute::GLModeValue)value);
}
// Read state attributes
size = in->readInt();
for(i=0;i<size;i++){
osg::StateAttribute* attribute;
int attributeID = in->peekInt();
if(attributeID == IVEBLENDFUNC){
attribute = new osg::BlendFunc();
((ive::BlendFunc*)(attribute))->read(in);
setAttribute(attribute, (osg::StateAttribute::OverrideValue)in->readInt());
}
else if(attributeID == IVEMATERIAL){
attribute = new osg::Material();
((ive::Material*)(attribute))->read(in);
setAttribute(attribute, (osg::StateAttribute::OverrideValue)in->readInt());
}
else if(attributeID == IVECULLFACE){
attribute = new osg::CullFace();
((ive::CullFace*)(attribute))->read(in);
setAttribute(attribute, (osg::StateAttribute::OverrideValue)in->readInt());
}
else{
throw Exception("Unkown StateAttribute in StateSet::read()");
}
}
// Read texture stateset mode.
int nUnits = in->readInt();
// Read state attributes
size = in->readInt();
for(i=0;i<size;i++){
osg::StateAttribute* attribute = in->readStateAttribute();
setAttribute(attribute, (osg::StateAttribute::OverrideValue)in->readInt());
}
// Read texture stateset mode.
int nUnits = in->readInt();
int unit;
for(unit=0;unit<nUnits;unit++){
size = in->readInt();
for(i=0;i<size;i++){
int mode = in->readInt();
int value = in->readInt();
setTextureMode(unit,(osg::StateAttribute::GLMode)mode, (osg::StateAttribute::GLModeValue)value);
}
}
for(unit=0;unit<nUnits;unit++){
size = in->readInt();
for(i=0;i<size;i++){
int mode = in->readInt();
int value = in->readInt();
setTextureMode(unit,(osg::StateAttribute::GLMode)mode, (osg::StateAttribute::GLModeValue)value);
}
}
// Read texture attributes.
nUnits = in->readInt();
for(unit=0;unit<nUnits;unit++){
size = in->readInt();
for(i=0;i<size;i++){
osg::StateAttribute* attribute;
int attributeID = in->peekInt();
if(attributeID == IVETEXTURE2D){
attribute = new osg::Texture2D();
((ive::Texture2D*)(attribute))->read(in);
setTextureAttribute(unit, attribute, (osg::StateAttribute::OverrideValue)in->readInt());
}
else if(attributeID == IVETEXTURECUBEMAP){
attribute = new osg::TextureCubeMap();
((ive::TextureCubeMap*)(attribute))->read(in);
setTextureAttribute(unit, attribute, (osg::StateAttribute::OverrideValue)in->readInt());
}
else if(attributeID == IVETEXENV){
attribute = new osg::TexEnv();
((ive::TexEnv*)(attribute))->read(in);
setTextureAttribute(unit, attribute, (osg::StateAttribute::OverrideValue)in->readInt());
}
else if(attributeID == IVETEXENVCOMBINE){
attribute = new osg::TexEnvCombine();
((ive::TexEnvCombine*)(attribute))->read(in);
setTextureAttribute(unit, attribute, (osg::StateAttribute::OverrideValue)in->readInt());
}
else if(attributeID == IVETEXGEN){
attribute = new osg::TexGen();
((ive::TexGen*)(attribute))->read(in);
setTextureAttribute(unit, attribute, (osg::StateAttribute::OverrideValue)in->readInt());
}
else{
throw Exception("Unkown Texture StateAttribute in StateSet::read()");
}
}
}
}
else{
throw Exception("StateSet::read(): Expected StateSet identification");
}
// Read texture attributes.
nUnits = in->readInt();
for(unit=0;unit<nUnits;unit++){
size = in->readInt();
for(i=0;i<size;i++){
osg::StateAttribute* attribute = in->readStateAttribute();
setTextureAttribute(unit, attribute, (osg::StateAttribute::OverrideValue)in->readInt());
}
}
}
else{
throw Exception("StateSet::read(): Expected StateSet identification");
}
}

View File

@ -38,7 +38,7 @@ void Texture2D::write(DataOutputStream* out){
// Include image data in stream
if(includeImg){
out->writeInt((int)getImage());
out->writeLong((long)getImage());
if(getImage())
((ive::Image*)getImage())->write(out);
}

View File

@ -41,27 +41,27 @@ void TextureCubeMap::write(DataOutputStream* out){
out->writeInt(getNumMipmapLevels());
// Write images if any
out->writeInt((int)getImage(osg::TextureCubeMap::POSITIVE_X));
out->writeLong((long)getImage(osg::TextureCubeMap::POSITIVE_X));
if(getImage(osg::TextureCubeMap::POSITIVE_X))
((ive::Image*)(getImage(osg::TextureCubeMap::POSITIVE_X)))->write(out);
out->writeInt((int)getImage(osg::TextureCubeMap::NEGATIVE_X));
out->writeLong((long)getImage(osg::TextureCubeMap::NEGATIVE_X));
if(getImage(osg::TextureCubeMap::NEGATIVE_X))
((ive::Image*)(getImage(osg::TextureCubeMap::NEGATIVE_X)))->write(out);
out->writeInt((int)getImage(osg::TextureCubeMap::POSITIVE_Y));
out->writeLong((long)getImage(osg::TextureCubeMap::POSITIVE_Y));
if(getImage(osg::TextureCubeMap::POSITIVE_Y))
((ive::Image*)(getImage(osg::TextureCubeMap::POSITIVE_Y)))->write(out);
out->writeInt((int)getImage(osg::TextureCubeMap::NEGATIVE_Y));
out->writeLong((long)getImage(osg::TextureCubeMap::NEGATIVE_Y));
if(getImage(osg::TextureCubeMap::NEGATIVE_Y))
((ive::Image*)(getImage(osg::TextureCubeMap::NEGATIVE_Y)))->write(out);
out->writeInt((int)getImage(osg::TextureCubeMap::POSITIVE_Z));
out->writeLong((long)getImage(osg::TextureCubeMap::POSITIVE_Z));
if(getImage(osg::TextureCubeMap::POSITIVE_Z))
((ive::Image*)(getImage(osg::TextureCubeMap::POSITIVE_Z)))->write(out);
out->writeInt((int)getImage(osg::TextureCubeMap::NEGATIVE_Z));
out->writeLong((long)getImage(osg::TextureCubeMap::NEGATIVE_Z));
if(getImage(osg::TextureCubeMap::NEGATIVE_Z))
((ive::Image*)(getImage(osg::TextureCubeMap::NEGATIVE_Z)))->write(out);

View File

@ -14,7 +14,7 @@
*/
#if defined(_MSC_VER)
#pragma warning( disable : 4786 )
#pragma warning( disable : 4786 )
#endif
#include <string>
@ -118,8 +118,14 @@ osgDB::ReaderWriter::ReadResult ReaderWriterOBJ::readNode(const std::string& fil
omtl->emmissive[2], omtl->emmissive[3]));
// note, osg shininess scales between 0.0 and 1.0.
mtl->setShininess(osg::Material::FRONT_AND_BACK, omtl->shininess);
mtl->setAlpha(osg::Material::FRONT_AND_BACK, omtl->alpha);
stateset->setAttribute(mtl);
if (omtl->alpha<1.0f) {
stateset->setMode(GL_BLEND,osg::StateAttribute::ON);
stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
}
if (omtl->textureName)
{
@ -158,9 +164,9 @@ osgDB::ReaderWriter::ReadResult ReaderWriterOBJ::readNode(const std::string& fil
osg::Group* osg_top = NULL;
if (obj->position[0] != 0.0f || obj->position[2] != 0.0f || obj->position[2] != 0.0f) {
osg::MatrixTransform* xform = new osg::MatrixTransform;
// note obj_x -> osg_x,
// obj_y -> osg_z,
// obj_z -> osg_y,
// note obj_x -> osg_x,
// obj_y -> osg_z,
// obj_z -> osg_y,
xform->setMatrix(osg::Matrix::translate(obj->position[0], obj->position[2], obj->position[1]));
osg_top = xform;
}

View File

@ -24,7 +24,7 @@
/* enums */
enum { X, Y, Z, W }; /* elements of a vertex */
enum { X, Y, Z, W }; /* elements of a vertex */
/* typedefs */
@ -151,7 +151,7 @@ _glmWeldVectors(GLfloat* vectors, unsigned int* numvectors, GLfloat epsilon)
for (i = 1; i <= *numvectors; i++) {
for (j = 1; j <= copied; j++) {
if (_glmEqual(&vectors[3 * i], &copies[3 * j], epsilon)) {
goto duplicate;
goto duplicate;
}
}
@ -159,7 +159,7 @@ _glmWeldVectors(GLfloat* vectors, unsigned int* numvectors, GLfloat epsilon)
copies[3 * copied + 0] = vectors[3 * i + 0];
copies[3 * copied + 1] = vectors[3 * i + 1];
copies[3 * copied + 2] = vectors[3 * i + 2];
j = copied; /* pass this along for below */
j = copied; /* pass this along for below */
copied++;
duplicate:
@ -338,6 +338,7 @@ _glmReadMTL(GLMmodel* model, char* name)
model->materials[i].specular[2] = 0.0f;
model->materials[i].textureName = NULL;
model->materials[i].textureReflection = false;
model->materials[i].alpha = 1.0f;
}
model->materials[0].name = strdup("default");
@ -361,30 +362,33 @@ _glmReadMTL(GLMmodel* model, char* name)
model->materials[nummaterials].shininess /= 1000.0;
model->materials[nummaterials].shininess *= 128.0;
break;
case 'd':
fscanf(file, "%f", &model->materials[nummaterials].alpha);
break;
case 'K':
switch(buf[1]) {
case 'd':
fscanf(file, "%f %f %f",
&model->materials[nummaterials].diffuse[0],
&model->materials[nummaterials].diffuse[1],
&model->materials[nummaterials].diffuse[2]);
break;
fscanf(file, "%f %f %f",
&model->materials[nummaterials].diffuse[0],
&model->materials[nummaterials].diffuse[1],
&model->materials[nummaterials].diffuse[2]);
break;
case 's':
fscanf(file, "%f %f %f",
&model->materials[nummaterials].specular[0],
&model->materials[nummaterials].specular[1],
&model->materials[nummaterials].specular[2]);
break;
fscanf(file, "%f %f %f",
&model->materials[nummaterials].specular[0],
&model->materials[nummaterials].specular[1],
&model->materials[nummaterials].specular[2]);
break;
case 'a':
fscanf(file, "%f %f %f",
&model->materials[nummaterials].ambient[0],
&model->materials[nummaterials].ambient[1],
&model->materials[nummaterials].ambient[2]);
break;
fscanf(file, "%f %f %f",
&model->materials[nummaterials].ambient[0],
&model->materials[nummaterials].ambient[1],
&model->materials[nummaterials].ambient[2]);
break;
default:
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
}
break;
@ -455,11 +459,11 @@ _glmWriteMTL(GLMmodel* model, char* modelpath, char* mtllibname)
material = &model->materials[i];
fprintf(file, "newmtl %s\n", material->name);
fprintf(file, "Ka %f %f %f\n",
material->ambient[0], material->ambient[1], material->ambient[2]);
material->ambient[0], material->ambient[1], material->ambient[2]);
fprintf(file, "Kd %f %f %f\n",
material->diffuse[0], material->diffuse[1], material->diffuse[2]);
material->diffuse[0], material->diffuse[1], material->diffuse[2]);
fprintf(file, "Ks %f %f %f\n",
material->specular[0],material->specular[1],material->specular[2]);
material->specular[0],material->specular[1],material->specular[2]);
fprintf(file, "Ns %f\n", material->shininess);
fprintf(file, "\n");
}
@ -493,11 +497,11 @@ static void createCompositeName(char* buf,char* compositeName)
static GLvoid
_glmFirstPass(GLMmodel* model, FILE* file)
{
unsigned int numvertices; /* number of vertices in model */
unsigned int numnormals; /* number of normals in model */
unsigned int numtexcoords; /* number of texcoords in model */
unsigned int numtriangles; /* number of triangles in model */
GLMgroup* group; /* current group */
unsigned int numvertices; /* number of vertices in model */
unsigned int numnormals; /* number of normals in model */
unsigned int numtexcoords; /* number of texcoords in model */
unsigned int numtriangles; /* number of triangles in model */
GLMgroup* group; /* current group */
unsigned v, n, t;
char buf[128];
@ -507,32 +511,32 @@ _glmFirstPass(GLMmodel* model, FILE* file)
numvertices = numnormals = numtexcoords = numtriangles = 0;
while(fscanf(file, "%s", buf) != EOF) {
switch(buf[0]) {
case '#': /* comment */
case '#': /* comment */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
case 'v': /* v, vn, vt */
case 'v': /* v, vn, vt */
switch(buf[1]) {
case '\0': /* vertex */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
numvertices++;
break;
case 'n': /* normal */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
numnormals++;
break;
case 't': /* texcoord */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
numtexcoords++;
break;
case '\0': /* vertex */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
numvertices++;
break;
case 'n': /* normal */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
numnormals++;
break;
case 't': /* texcoord */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
numtexcoords++;
break;
default:
printf("_glmFirstPass(): Unknown token \"%s\".\n", buf);
//exit(1);
return;
break;
printf("_glmFirstPass(): Unknown token \"%s\".\n", buf);
//exit(1);
return;
break;
}
break;
case 'm':
@ -545,7 +549,7 @@ _glmFirstPass(GLMmodel* model, FILE* file)
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
case 'g': /* group */
case 'g': /* group */
{
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
@ -556,51 +560,51 @@ _glmFirstPass(GLMmodel* model, FILE* file)
group = _glmAddGroup(model, compositeName);
}
break;
case 'f': /* face */
case 'f': /* face */
v = n = t = 0;
fscanf(file, "%s", buf);
/* can be one of %d, %d//%d, %d/%d, %d/%d/%d %d//%d */
if (strstr(buf, "//")) {
/* v//n */
sscanf(buf, "%d//%d", &v, &n);
fscanf(file, "%d//%d", &v, &n);
fscanf(file, "%d//%d", &v, &n);
numtriangles++;
group->numtriangles++;
while(fscanf(file, "%d//%d", &v, &n) > 0) {
numtriangles++;
group->numtriangles++;
}
/* v//n */
sscanf(buf, "%d//%d", &v, &n);
fscanf(file, "%d//%d", &v, &n);
fscanf(file, "%d//%d", &v, &n);
numtriangles++;
group->numtriangles++;
while(fscanf(file, "%d//%d", &v, &n) > 0) {
numtriangles++;
group->numtriangles++;
}
} else if (sscanf(buf, "%d/%d/%d", &v, &t, &n) == 3) {
/* v/t/n */
fscanf(file, "%d/%d/%d", &v, &t, &n);
fscanf(file, "%d/%d/%d", &v, &t, &n);
numtriangles++;
group->numtriangles++;
while(fscanf(file, "%d/%d/%d", &v, &t, &n) > 0) {
numtriangles++;
group->numtriangles++;
}
/* v/t/n */
fscanf(file, "%d/%d/%d", &v, &t, &n);
fscanf(file, "%d/%d/%d", &v, &t, &n);
numtriangles++;
group->numtriangles++;
while(fscanf(file, "%d/%d/%d", &v, &t, &n) > 0) {
numtriangles++;
group->numtriangles++;
}
} else if (sscanf(buf, "%d/%d", &v, &t) == 2) {
/* v/t */
fscanf(file, "%d/%d", &v, &t);
fscanf(file, "%d/%d", &v, &t);
numtriangles++;
group->numtriangles++;
while(fscanf(file, "%d/%d", &v, &t) > 0) {
numtriangles++;
group->numtriangles++;
}
/* v/t */
fscanf(file, "%d/%d", &v, &t);
fscanf(file, "%d/%d", &v, &t);
numtriangles++;
group->numtriangles++;
while(fscanf(file, "%d/%d", &v, &t) > 0) {
numtriangles++;
group->numtriangles++;
}
} else {
/* v */
fscanf(file, "%d", &v);
fscanf(file, "%d", &v);
numtriangles++;
group->numtriangles++;
while(fscanf(file, "%d", &v) > 0) {
numtriangles++;
group->numtriangles++;
}
/* v */
fscanf(file, "%d", &v);
fscanf(file, "%d", &v);
numtriangles++;
group->numtriangles++;
while(fscanf(file, "%d", &v) > 0) {
numtriangles++;
group->numtriangles++;
}
}
break;
@ -644,15 +648,15 @@ _glmFirstPass(GLMmodel* model, FILE* file)
static GLvoid
_glmSecondPass(GLMmodel* model, FILE* file)
{
unsigned int numvertices; /* number of vertices in model */
unsigned int numnormals; /* number of normals in model */
unsigned int numtexcoords; /* number of texcoords in model */
unsigned int numtriangles; /* number of triangles in model */
GLfloat* vertices; /* array of vertices */
GLfloat* normals; /* array of normals */
GLfloat* texcoords; /* array of texture coordinates */
GLMgroup* group; /* current group pointer */
unsigned int material; /* current material */
unsigned int numvertices; /* number of vertices in model */
unsigned int numnormals; /* number of normals in model */
unsigned int numtexcoords; /* number of texcoords in model */
unsigned int numtriangles; /* number of triangles in model */
GLfloat* vertices; /* array of vertices */
GLfloat* normals; /* array of normals */
GLfloat* texcoords; /* array of texture coordinates */
GLMgroup* group; /* current group pointer */
unsigned int material; /* current material */
unsigned int v, n, t;
char buf[128];
@ -674,32 +678,32 @@ _glmSecondPass(GLMmodel* model, FILE* file)
while(fscanf(file, "%s", buf) != EOF) {
char c = buf[0];
switch(c) {
case '#': /* comment */
case '#': /* comment */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
case 'v': /* v, vn, vt */
case 'v': /* v, vn, vt */
switch(buf[1]) {
case '\0': /* vertex */
fscanf(file, "%f %f %f",
&vertices[3 * numvertices + X],
&vertices[3 * numvertices + Y],
&vertices[3 * numvertices + Z]);
numvertices++;
break;
case 'n': /* normal */
fscanf(file, "%f %f %f",
&normals[3 * numnormals + X],
&normals[3 * numnormals + Y],
&normals[3 * numnormals + Z]);
numnormals++;
break;
case 't': /* texcoord */
fscanf(file, "%f %f",
&texcoords[2 * numtexcoords + X],
&texcoords[2 * numtexcoords + Y]);
numtexcoords++;
break;
case '\0': /* vertex */
fscanf(file, "%f %f %f",
&vertices[3 * numvertices + X],
&vertices[3 * numvertices + Y],
&vertices[3 * numvertices + Z]);
numvertices++;
break;
case 'n': /* normal */
fscanf(file, "%f %f %f",
&normals[3 * numnormals + X],
&normals[3 * numnormals + Y],
&normals[3 * numnormals + Z]);
numnormals++;
break;
case 't': /* texcoord */
fscanf(file, "%f %f",
&texcoords[2 * numtexcoords + X],
&texcoords[2 * numtexcoords + Y]);
numtexcoords++;
break;
}
break;
case 'u':
@ -714,7 +718,7 @@ _glmSecondPass(GLMmodel* model, FILE* file)
if (previousLineWas_g || firstGroup) group->material = material;
break;
case 'g': /* group */
case 'g': /* group */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
char compositeName[128];
@ -724,102 +728,102 @@ _glmSecondPass(GLMmodel* model, FILE* file)
group->material = material;
firstGroup = false;
break;
case 'f': /* face */
case 'f': /* face */
v = n = t = 0;
fscanf(file, "%s", buf);
/* can be one of %d, %d//%d, %d/%d, %d/%d/%d %d//%d */
if (strstr(buf, "//")) {
/* v//n */
sscanf(buf, "%d//%d", &v, &n);
T(numtriangles).vindices[0] = v;
T(numtriangles).nindices[0] = n;
fscanf(file, "%d//%d", &v, &n);
T(numtriangles).vindices[1] = v;
T(numtriangles).nindices[1] = n;
fscanf(file, "%d//%d", &v, &n);
T(numtriangles).vindices[2] = v;
T(numtriangles).nindices[2] = n;
group->triangles[group->numtriangles++] = numtriangles;
numtriangles++;
while(fscanf(file, "%d//%d", &v, &n) > 0) {
T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0];
T(numtriangles).nindices[0] = T(numtriangles-1).nindices[0];
T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2];
T(numtriangles).nindices[1] = T(numtriangles-1).nindices[2];
T(numtriangles).vindices[2] = v;
T(numtriangles).nindices[2] = n;
group->triangles[group->numtriangles++] = numtriangles;
numtriangles++;
}
/* v//n */
sscanf(buf, "%d//%d", &v, &n);
T(numtriangles).vindices[0] = v;
T(numtriangles).nindices[0] = n;
fscanf(file, "%d//%d", &v, &n);
T(numtriangles).vindices[1] = v;
T(numtriangles).nindices[1] = n;
fscanf(file, "%d//%d", &v, &n);
T(numtriangles).vindices[2] = v;
T(numtriangles).nindices[2] = n;
group->triangles[group->numtriangles++] = numtriangles;
numtriangles++;
while(fscanf(file, "%d//%d", &v, &n) > 0) {
T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0];
T(numtriangles).nindices[0] = T(numtriangles-1).nindices[0];
T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2];
T(numtriangles).nindices[1] = T(numtriangles-1).nindices[2];
T(numtriangles).vindices[2] = v;
T(numtriangles).nindices[2] = n;
group->triangles[group->numtriangles++] = numtriangles;
numtriangles++;
}
} else if (sscanf(buf, "%d/%d/%d", &v, &t, &n) == 3) {
/* v/t/n */
T(numtriangles).vindices[0] = v;
T(numtriangles).tindices[0] = t;
T(numtriangles).nindices[0] = n;
fscanf(file, "%d/%d/%d", &v, &t, &n);
T(numtriangles).vindices[1] = v;
T(numtriangles).tindices[1] = t;
T(numtriangles).nindices[1] = n;
fscanf(file, "%d/%d/%d", &v, &t, &n);
T(numtriangles).vindices[2] = v;
T(numtriangles).tindices[2] = t;
T(numtriangles).nindices[2] = n;
group->triangles[group->numtriangles++] = numtriangles;
group->hastexcoords = true;
numtriangles++;
while(fscanf(file, "%d/%d/%d", &v, &t, &n) > 0) {
T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0];
T(numtriangles).tindices[0] = T(numtriangles-1).tindices[0];
T(numtriangles).nindices[0] = T(numtriangles-1).nindices[0];
T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2];
T(numtriangles).tindices[1] = T(numtriangles-1).tindices[2];
T(numtriangles).nindices[1] = T(numtriangles-1).nindices[2];
T(numtriangles).vindices[2] = v;
T(numtriangles).tindices[2] = t;
T(numtriangles).nindices[2] = n;
group->triangles[group->numtriangles++] = numtriangles;
numtriangles++;
}
/* v/t/n */
T(numtriangles).vindices[0] = v;
T(numtriangles).tindices[0] = t;
T(numtriangles).nindices[0] = n;
fscanf(file, "%d/%d/%d", &v, &t, &n);
T(numtriangles).vindices[1] = v;
T(numtriangles).tindices[1] = t;
T(numtriangles).nindices[1] = n;
fscanf(file, "%d/%d/%d", &v, &t, &n);
T(numtriangles).vindices[2] = v;
T(numtriangles).tindices[2] = t;
T(numtriangles).nindices[2] = n;
group->triangles[group->numtriangles++] = numtriangles;
group->hastexcoords = true;
numtriangles++;
while(fscanf(file, "%d/%d/%d", &v, &t, &n) > 0) {
T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0];
T(numtriangles).tindices[0] = T(numtriangles-1).tindices[0];
T(numtriangles).nindices[0] = T(numtriangles-1).nindices[0];
T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2];
T(numtriangles).tindices[1] = T(numtriangles-1).tindices[2];
T(numtriangles).nindices[1] = T(numtriangles-1).nindices[2];
T(numtriangles).vindices[2] = v;
T(numtriangles).tindices[2] = t;
T(numtriangles).nindices[2] = n;
group->triangles[group->numtriangles++] = numtriangles;
numtriangles++;
}
} else if (sscanf(buf, "%d/%d", &v, &t) == 2) {
/* v/t */
T(numtriangles).vindices[0] = v;
T(numtriangles).tindices[0] = t;
fscanf(file, "%d/%d", &v, &t);
T(numtriangles).vindices[1] = v;
T(numtriangles).tindices[1] = t;
fscanf(file, "%d/%d", &v, &t);
T(numtriangles).vindices[2] = v;
T(numtriangles).tindices[2] = t;
group->triangles[group->numtriangles++] = numtriangles;
group->hastexcoords = true;
numtriangles++;
while(fscanf(file, "%d/%d", &v, &t) > 0) {
T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0];
T(numtriangles).tindices[0] = T(numtriangles-1).tindices[0];
T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2];
T(numtriangles).tindices[1] = T(numtriangles-1).tindices[2];
T(numtriangles).vindices[2] = v;
T(numtriangles).tindices[2] = t;
group->triangles[group->numtriangles++] = numtriangles;
numtriangles++;
}
/* v/t */
T(numtriangles).vindices[0] = v;
T(numtriangles).tindices[0] = t;
fscanf(file, "%d/%d", &v, &t);
T(numtriangles).vindices[1] = v;
T(numtriangles).tindices[1] = t;
fscanf(file, "%d/%d", &v, &t);
T(numtriangles).vindices[2] = v;
T(numtriangles).tindices[2] = t;
group->triangles[group->numtriangles++] = numtriangles;
group->hastexcoords = true;
numtriangles++;
while(fscanf(file, "%d/%d", &v, &t) > 0) {
T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0];
T(numtriangles).tindices[0] = T(numtriangles-1).tindices[0];
T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2];
T(numtriangles).tindices[1] = T(numtriangles-1).tindices[2];
T(numtriangles).vindices[2] = v;
T(numtriangles).tindices[2] = t;
group->triangles[group->numtriangles++] = numtriangles;
numtriangles++;
}
} else {
/* v */
sscanf(buf, "%d", &v);
T(numtriangles).vindices[0] = v;
fscanf(file, "%d", &v);
T(numtriangles).vindices[1] = v;
fscanf(file, "%d", &v);
T(numtriangles).vindices[2] = v;
group->triangles[group->numtriangles++] = numtriangles;
numtriangles++;
while(fscanf(file, "%d", &v) > 0) {
T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0];
T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2];
T(numtriangles).vindices[2] = v;
group->triangles[group->numtriangles++] = numtriangles;
numtriangles++;
}
/* v */
sscanf(buf, "%d", &v);
T(numtriangles).vindices[0] = v;
fscanf(file, "%d", &v);
T(numtriangles).vindices[1] = v;
fscanf(file, "%d", &v);
T(numtriangles).vindices[2] = v;
group->triangles[group->numtriangles++] = numtriangles;
numtriangles++;
while(fscanf(file, "%d", &v) > 0) {
T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0];
T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2];
T(numtriangles).vindices[2] = v;
group->triangles[group->numtriangles++] = numtriangles;
numtriangles++;
}
}
break;
@ -837,10 +841,10 @@ _glmSecondPass(GLMmodel* model, FILE* file)
#if 0
/* announce the memory requirements */
printf(" Memory: %d bytes\n",
numvertices * 3*sizeof(GLfloat) +
numnormals * 3*sizeof(GLfloat) * (numnormals ? 1 : 0) +
numtexcoords * 3*sizeof(GLfloat) * (numtexcoords ? 1 : 0) +
numtriangles * sizeof(GLMtriangle));
numvertices * 3*sizeof(GLfloat) +
numnormals * 3*sizeof(GLfloat) * (numnormals ? 1 : 0) +
numtexcoords * 3*sizeof(GLfloat) * (numtexcoords ? 1 : 0) +
numtriangles * sizeof(GLMtriangle));
#endif
}
@ -1042,7 +1046,7 @@ glmFacetNormals(GLMmodel* model)
/* allocate memory for the new facet normals */
model->numfacetnorms = model->numtriangles;
model->facetnorms = (GLfloat*)malloc(sizeof(GLfloat) *
3 * (model->numfacetnorms + 1));
3 * (model->numfacetnorms + 1));
for (i = 0; i < model->numtriangles; i++) {
model->triangles[i].findex = i+1;
@ -1148,15 +1152,15 @@ glmVertexNormals(GLMmodel* model, GLfloat angle)
angle -- or, said another way, the angle between the two
facet normals is less than (or equal to) the threshold angle */
dot = _glmDot(&model->facetnorms[3 * T(node->index).findex],
&model->facetnorms[3 * T(members[i]->index).findex]);
&model->facetnorms[3 * T(members[i]->index).findex]);
if (dot > cos_angle) {
node->averaged = GL_TRUE;
average[0] += model->facetnorms[3 * T(node->index).findex + 0];
average[1] += model->facetnorms[3 * T(node->index).findex + 1];
average[2] += model->facetnorms[3 * T(node->index).findex + 2];
avg = 1; /* we averaged at least one normal! */
node->averaged = GL_TRUE;
average[0] += model->facetnorms[3 * T(node->index).findex + 0];
average[1] += model->facetnorms[3 * T(node->index).findex + 1];
average[2] += model->facetnorms[3 * T(node->index).findex + 2];
avg = 1; /* we averaged at least one normal! */
} else {
node->averaged = GL_FALSE;
node->averaged = GL_FALSE;
}
node = node->next;
}
@ -1177,28 +1181,28 @@ glmVertexNormals(GLMmodel* model, GLfloat angle)
node = members[i];
while (node) {
if (node->averaged) {
/* if this node was averaged, use the average normal */
if (T(node->index).vindices[0] == i)
T(node->index).nindices[0] = avg;
else if (T(node->index).vindices[1] == i)
T(node->index).nindices[1] = avg;
else if (T(node->index).vindices[2] == i)
T(node->index).nindices[2] = avg;
/* if this node was averaged, use the average normal */
if (T(node->index).vindices[0] == i)
T(node->index).nindices[0] = avg;
else if (T(node->index).vindices[1] == i)
T(node->index).nindices[1] = avg;
else if (T(node->index).vindices[2] == i)
T(node->index).nindices[2] = avg;
} else {
/* if this node wasn't averaged, use the facet normal */
model->normals[3 * numnormals + 0] =
model->facetnorms[3 * T(node->index).findex + 0];
model->normals[3 * numnormals + 1] =
model->facetnorms[3 * T(node->index).findex + 1];
model->normals[3 * numnormals + 2] =
model->facetnorms[3 * T(node->index).findex + 2];
if (T(node->index).vindices[0] == i)
T(node->index).nindices[0] = numnormals;
else if (T(node->index).vindices[1] == i)
T(node->index).nindices[1] = numnormals;
else if (T(node->index).vindices[2] == i)
T(node->index).nindices[2] = numnormals;
numnormals++;
/* if this node wasn't averaged, use the facet normal */
model->normals[3 * numnormals + 0] =
model->facetnorms[3 * T(node->index).findex + 0];
model->normals[3 * numnormals + 1] =
model->facetnorms[3 * T(node->index).findex + 1];
model->normals[3 * numnormals + 2] =
model->facetnorms[3 * T(node->index).findex + 2];
if (T(node->index).vindices[0] == i)
T(node->index).nindices[0] = numnormals;
else if (T(node->index).vindices[1] == i)
T(node->index).nindices[1] = numnormals;
else if (T(node->index).vindices[2] == i)
T(node->index).nindices[2] = numnormals;
numnormals++;
}
node = node->next;
}
@ -1280,7 +1284,7 @@ glmLinearTexture(GLMmodel* model)
#if 0
printf("glmLinearTexture(): generated %d linear texture coordinates\n",
model->numtexcoords);
model->numtexcoords);
#endif
}
@ -1312,32 +1316,32 @@ glmSpheremapTexture(GLMmodel* model)
/* do the calculations */
for (i = 1; i <= model->numnormals; i++) {
z = model->normals[3 * i + 0]; /* re-arrange for pole distortion */
z = model->normals[3 * i + 0]; /* re-arrange for pole distortion */
y = model->normals[3 * i + 1];
x = model->normals[3 * i + 2];
r = sqrtf((x * x) + (y * y));
rho = sqrtf((r * r) + (z * z));
if(r == 0.0f) {
theta = 0.0f;
phi = 0.0f;
theta = 0.0f;
phi = 0.0f;
} else {
if(z == 0.0)
phi = 3.14159265f / 2.0f;
phi = 3.14159265f / 2.0f;
else
phi = acosf(z / rho);
phi = acosf(z / rho);
#if WE_DONT_NEED_THIS_CODE
if(x == 0.0)
theta = 3.14159265f / 2.0f; /* asin(y / r); */
theta = 3.14159265f / 2.0f; /* asin(y / r); */
else
theta = acos(x / r);
theta = acos(x / r);
#endif
if(y == 0.0)
theta = 3.141592365f / 2.0f; /* acos(x / r); */
theta = 3.141592365f / 2.0f; /* acos(x / r); */
else
theta = asinf(y / r) + 3.14159265f / 2.0f;
theta = asinf(y / r) + 3.14159265f / 2.0f;
}
model->texcoords[2 * i + 0] = theta / 3.14159265f;
@ -1357,7 +1361,7 @@ glmSpheremapTexture(GLMmodel* model)
#if 0
printf("glmSpheremapTexture(): generated %d spheremap texture coordinates\n",
model->numtexcoords);
model->numtexcoords);
#endif
}
@ -1415,9 +1419,9 @@ glmReadOBJ(char* filename)
file = fopen(filename, "r");
if (!file) {
fprintf(stderr, "glmReadOBJ() failed: can't open data file \"%s\".\n",
filename);
filename);
//exit(1);
return NULL;
return NULL;
}
#if 0
@ -1453,16 +1457,16 @@ glmReadOBJ(char* filename)
/* allocate memory */
model->vertices = (GLfloat*)malloc(sizeof(GLfloat) *
3 * (model->numvertices + 1));
3 * (model->numvertices + 1));
model->triangles = (GLMtriangle*)malloc(sizeof(GLMtriangle) *
model->numtriangles);
model->numtriangles);
if (model->numnormals) {
model->normals = (GLfloat*)malloc(sizeof(GLfloat) *
3 * (model->numnormals + 1));
3 * (model->numnormals + 1));
}
if (model->numtexcoords) {
model->texcoords = (GLfloat*)malloc(sizeof(GLfloat) *
2 * (model->numtexcoords + 1));
2 * (model->numtexcoords + 1));
}
/* rewind to beginning of file and read in the data this pass */
@ -1503,22 +1507,22 @@ glmWriteOBJ(GLMmodel* model, char* filename, unsigned int mode)
/* do a bit of warning */
if (mode & GLM_FLAT && !model->facetnorms) {
printf("glmWriteOBJ() warning: flat normal output requested "
"with no facet normals defined.\n");
"with no facet normals defined.\n");
mode &= ~GLM_FLAT;
}
if (mode & GLM_SMOOTH && !model->normals) {
printf("glmWriteOBJ() warning: smooth normal output requested "
"with no normals defined.\n");
"with no normals defined.\n");
mode &= ~GLM_SMOOTH;
}
if (mode & GLM_TEXTURE && !model->texcoords) {
printf("glmWriteOBJ() warning: texture coordinate output requested "
"with no texture coordinates defined.\n");
"with no texture coordinates defined.\n");
mode &= ~GLM_TEXTURE;
}
if (mode & GLM_FLAT && mode & GLM_SMOOTH) {
printf("glmWriteOBJ() warning: flat normal output requested "
"and smooth normal output requested (using smooth).\n");
"and smooth normal output requested (using smooth).\n");
mode &= ~GLM_FLAT;
}
@ -1526,9 +1530,9 @@ glmWriteOBJ(GLMmodel* model, char* filename, unsigned int mode)
file = fopen(filename, "w");
if (!file) {
fprintf(stderr, "glmWriteOBJ() failed: can't open file \"%s\" to write.\n",
filename);
filename);
//exit(1);
return;
return;
}
/* spit out a header */
@ -1550,9 +1554,9 @@ glmWriteOBJ(GLMmodel* model, char* filename, unsigned int mode)
fprintf(file, "# %d vertices\n", model->numvertices);
for (i = 1; i <= model->numvertices; i++) {
fprintf(file, "v %f %f %f\n",
model->vertices[3 * i + 0],
model->vertices[3 * i + 1],
model->vertices[3 * i + 2]);
model->vertices[3 * i + 0],
model->vertices[3 * i + 1],
model->vertices[3 * i + 2]);
}
/* spit out the smooth/flat normals */
@ -1561,18 +1565,18 @@ glmWriteOBJ(GLMmodel* model, char* filename, unsigned int mode)
fprintf(file, "# %d normals\n", model->numnormals);
for (i = 1; i <= model->numnormals; i++) {
fprintf(file, "vn %f %f %f\n",
model->normals[3 * i + 0],
model->normals[3 * i + 1],
model->normals[3 * i + 2]);
model->normals[3 * i + 0],
model->normals[3 * i + 1],
model->normals[3 * i + 2]);
}
} else if (mode & GLM_FLAT) {
fprintf(file, "\n");
fprintf(file, "# %d normals\n", model->numfacetnorms);
for (i = 1; i <= model->numnormals; i++) {
fprintf(file, "vn %f %f %f\n",
model->facetnorms[3 * i + 0],
model->facetnorms[3 * i + 1],
model->facetnorms[3 * i + 2]);
model->facetnorms[3 * i + 0],
model->facetnorms[3 * i + 1],
model->facetnorms[3 * i + 2]);
}
}
@ -1582,8 +1586,8 @@ glmWriteOBJ(GLMmodel* model, char* filename, unsigned int mode)
fprintf(file, "# %d texcoords\n", model->numtexcoords);
for (i = 1; i <= model->numtexcoords; i++) {
fprintf(file, "vt %f %f\n",
model->texcoords[2 * i + 0],
model->texcoords[2 * i + 1]);
model->texcoords[2 * i + 0],
model->texcoords[2 * i + 1]);
}
}
@ -1599,53 +1603,53 @@ glmWriteOBJ(GLMmodel* model, char* filename, unsigned int mode)
fprintf(file, "usemtl %s\n", model->materials[group->material].name);
for (i = 0; i < group->numtriangles; i++) {
if (mode & GLM_SMOOTH && mode & GLM_TEXTURE) {
fprintf(file, "f %d/%d/%d %d/%d/%d %d/%d/%d\n",
T(group->triangles[i]).vindices[0],
T(group->triangles[i]).nindices[0],
T(group->triangles[i]).tindices[0],
T(group->triangles[i]).vindices[1],
T(group->triangles[i]).nindices[1],
T(group->triangles[i]).tindices[1],
T(group->triangles[i]).vindices[2],
T(group->triangles[i]).nindices[2],
T(group->triangles[i]).tindices[2]);
fprintf(file, "f %d/%d/%d %d/%d/%d %d/%d/%d\n",
T(group->triangles[i]).vindices[0],
T(group->triangles[i]).nindices[0],
T(group->triangles[i]).tindices[0],
T(group->triangles[i]).vindices[1],
T(group->triangles[i]).nindices[1],
T(group->triangles[i]).tindices[1],
T(group->triangles[i]).vindices[2],
T(group->triangles[i]).nindices[2],
T(group->triangles[i]).tindices[2]);
} else if (mode & GLM_FLAT && mode & GLM_TEXTURE) {
fprintf(file, "f %d/%d %d/%d %d/%d\n",
T(group->triangles[i]).vindices[0],
T(group->triangles[i]).findex,
T(group->triangles[i]).vindices[1],
T(group->triangles[i]).findex,
T(group->triangles[i]).vindices[2],
T(group->triangles[i]).findex);
fprintf(file, "f %d/%d %d/%d %d/%d\n",
T(group->triangles[i]).vindices[0],
T(group->triangles[i]).findex,
T(group->triangles[i]).vindices[1],
T(group->triangles[i]).findex,
T(group->triangles[i]).vindices[2],
T(group->triangles[i]).findex);
} else if (mode & GLM_TEXTURE) {
fprintf(file, "f %d/%d %d/%d %d/%d\n",
T(group->triangles[i]).vindices[0],
T(group->triangles[i]).tindices[0],
T(group->triangles[i]).vindices[1],
T(group->triangles[i]).tindices[1],
T(group->triangles[i]).vindices[2],
T(group->triangles[i]).tindices[2]);
fprintf(file, "f %d/%d %d/%d %d/%d\n",
T(group->triangles[i]).vindices[0],
T(group->triangles[i]).tindices[0],
T(group->triangles[i]).vindices[1],
T(group->triangles[i]).tindices[1],
T(group->triangles[i]).vindices[2],
T(group->triangles[i]).tindices[2]);
} else if (mode & GLM_SMOOTH) {
fprintf(file, "f %d//%d %d//%d %d//%d\n",
T(group->triangles[i]).vindices[0],
T(group->triangles[i]).nindices[0],
T(group->triangles[i]).vindices[1],
T(group->triangles[i]).nindices[1],
T(group->triangles[i]).vindices[2],
T(group->triangles[i]).nindices[2]);
fprintf(file, "f %d//%d %d//%d %d//%d\n",
T(group->triangles[i]).vindices[0],
T(group->triangles[i]).nindices[0],
T(group->triangles[i]).vindices[1],
T(group->triangles[i]).nindices[1],
T(group->triangles[i]).vindices[2],
T(group->triangles[i]).nindices[2]);
} else if (mode & GLM_FLAT) {
fprintf(file, "f %d//%d %d//%d %d//%d\n",
T(group->triangles[i]).vindices[0],
T(group->triangles[i]).findex,
T(group->triangles[i]).vindices[1],
T(group->triangles[i]).findex,
T(group->triangles[i]).vindices[2],
T(group->triangles[i]).findex);
fprintf(file, "f %d//%d %d//%d %d//%d\n",
T(group->triangles[i]).vindices[0],
T(group->triangles[i]).findex,
T(group->triangles[i]).vindices[1],
T(group->triangles[i]).findex,
T(group->triangles[i]).vindices[2],
T(group->triangles[i]).findex);
} else {
fprintf(file, "f %d %d %d\n",
T(group->triangles[i]).vindices[0],
T(group->triangles[i]).vindices[1],
T(group->triangles[i]).vindices[2]);
fprintf(file, "f %d %d %d\n",
T(group->triangles[i]).vindices[0],
T(group->triangles[i]).vindices[1],
T(group->triangles[i]).vindices[2]);
}
}
fprintf(file, "\n");
@ -1677,7 +1681,7 @@ glmWeld(GLMmodel* model, GLfloat epsilon)
copies = _glmWeldVectors(vectors, &numvectors, epsilon);
printf("glmWeld(): %d redundant vertices.\n",
model->numvertices - numvectors - 1);
model->numvertices - numvectors - 1);
for (i = 0; i < model->numtriangles; i++) {
T(i).vindices[0] = (unsigned int)vectors[3 * T(i).vindices[0] + 0];
@ -1691,7 +1695,7 @@ glmWeld(GLMmodel* model, GLfloat epsilon)
/* allocate space for the new vertices */
model->numvertices = numvectors;
model->vertices = (GLfloat*)malloc(sizeof(GLfloat) *
3 * (model->numvertices + 1));
3 * (model->numvertices + 1));
/* copy the optimized vertices into the actual vertex list */
for (i = 1; i <= model->numvertices; i++) {
@ -1712,7 +1716,7 @@ glmWeld(GLMmodel* model, GLfloat epsilon)
copies = _glmOptimizeVectors(vectors, &numvectors);
printf("glmOptimize(): %d redundant normals.\n",
model->numnormals - numvectors);
model->numnormals - numvectors);
for (i = 0; i < model->numtriangles; i++) {
T(i).nindices[0] = (unsigned int)vectors[3 * T(i).nindices[0] + 0];
@ -1726,7 +1730,7 @@ glmWeld(GLMmodel* model, GLfloat epsilon)
/* allocate space for the new normals */
model->numnormals = numvectors;
model->normals = (GLfloat*)malloc(sizeof(GLfloat) *
3 * (model->numnormals + 1));
3 * (model->numnormals + 1));
/* copy the optimized vertices into the actual vertex list */
for (i = 1; i <= model->numnormals; i++) {
@ -1745,7 +1749,7 @@ glmWeld(GLMmodel* model, GLfloat epsilon)
copies = _glmOptimizeVectors(vectors, &numvectors);
printf("glmOptimize(): %d redundant texcoords.\n",
model->numtexcoords - numvectors);
model->numtexcoords - numvectors);
for (i = 0; i < model->numtriangles; i++) {
for (j = 0; j < 3; j++) {
@ -1759,7 +1763,7 @@ glmWeld(GLMmodel* model, GLfloat epsilon)
/* allocate space for the new texcoords */
model->numtexcoords = numvectors;
model->texcoords = (GLfloat*)malloc(sizeof(GLfloat) *
2 * (model->numtexcoords + 1));
2 * (model->numtexcoords + 1));
/* copy the optimized vertices into the actual vertex list */
for (i = 1; i <= model->numtexcoords; i++) {
@ -1778,9 +1782,9 @@ glmWeld(GLMmodel* model, GLfloat epsilon)
for (i = 1; i <= model->numvertices; i++) {
for (j = 0; j < model->numtriangles; i++) {
if (T(j).vindices[0] == i ||
T(j).vindices[1] == i ||
T(j).vindices[1] == i)
break;
T(j).vindices[1] == i ||
T(j).vindices[1] == i)
break;
}
}
#endif

View File

@ -24,12 +24,12 @@
/* defines */
#define GLM_NONE (0) /* render with only vertices */
#define GLM_FLAT (1 << 0) /* render with facet normals */
#define GLM_SMOOTH (1 << 1) /* render with vertex normals */
#define GLM_TEXTURE (1 << 2) /* render with texture coords */
#define GLM_COLOR (1 << 3) /* render with colors */
#define GLM_MATERIAL (1 << 4) /* render with materials */
#define GLM_NONE (0) /* render with only vertices */
#define GLM_FLAT (1 << 0) /* render with facet normals */
#define GLM_SMOOTH (1 << 1) /* render with vertex normals */
#define GLM_TEXTURE (1 << 2) /* render with texture coords */
#define GLM_COLOR (1 << 3) /* render with colors */
#define GLM_MATERIAL (1 << 4) /* render with materials */
/* structs */
@ -38,25 +38,27 @@
*/
struct GLMmaterial
{
char* name; /* name of material */
GLfloat diffuse[4]; /* diffuse component */
GLfloat ambient[4]; /* ambient component */
GLfloat specular[4]; /* specular component */
GLfloat emmissive[4]; /* emmissive component */
GLfloat shininess; /* specular exponent */
char* name; /* name of material */
GLfloat diffuse[4]; /* diffuse component */
GLfloat ambient[4]; /* ambient component */
GLfloat specular[4]; /* specular component */
GLfloat emmissive[4]; /* emmissive component */
GLfloat shininess; /* specular exponent */
char* textureName; /* name of any attached texture, add by RO */
bool textureReflection; /* true if texture is a reflection map */
float alpha; /* alpha */
void init()
{
name = NULL;
diffuse[0] = diffuse[1] = diffuse[2] = 0.8f; diffuse[3] = 1.0f;
ambient[0] = ambient[1] = ambient[2] = 0.2f; ambient[3] = 1.0f;
specular[0] = specular[1] = specular[2] = 0.0f; specular[3] = 1.0f;
emmissive[0] = emmissive[1] = emmissive[2] = 0.0f; emmissive[3] = 1.0f;
shininess = 0.0f;
textureName = NULL;
textureReflection = false;
name = NULL;
diffuse[0] = diffuse[1] = diffuse[2] = 0.8f; diffuse[3] = 1.0f;
ambient[0] = ambient[1] = ambient[2] = 0.2f; ambient[3] = 1.0f;
specular[0] = specular[1] = specular[2] = 0.0f; specular[3] = 1.0f;
emmissive[0] = emmissive[1] = emmissive[2] = 0.0f; emmissive[3] = 1.0f;
shininess = 0.0f;
textureName = NULL;
textureReflection = false;
alpha = 1.0f;
}
};
@ -64,97 +66,97 @@ struct GLMmaterial
/* GLMtriangle: Structure that defines a triangle in a model.
*/
struct GLMtriangle {
unsigned int vindices[3]; /* array of triangle vertex indices */
unsigned int nindices[3]; /* array of triangle normal indices */
unsigned int tindices[3]; /* array of triangle texcoord indices*/
unsigned int findex; /* index of triangle facet normal */
unsigned int vindices[3]; /* array of triangle vertex indices */
unsigned int nindices[3]; /* array of triangle normal indices */
unsigned int tindices[3]; /* array of triangle texcoord indices*/
unsigned int findex; /* index of triangle facet normal */
void init()
{
vindices[0] = vindices[2] = vindices[2] = 0 ;
nindices[0] = nindices[2] = nindices[2] = 0 ;
tindices[0] = tindices[2] = tindices[2] = 0 ;
findex=0;
vindices[0] = vindices[2] = vindices[2] = 0 ;
nindices[0] = nindices[2] = nindices[2] = 0 ;
tindices[0] = tindices[2] = tindices[2] = 0 ;
findex=0;
}
};
/* GLMgroup: Structure that defines a group in a model.
*/
struct GLMgroup {
char* name; /* name of this group */
unsigned int numtriangles; /* number of triangles in this group */
unsigned int* triangles; /* array of triangle indices */
char* name; /* name of this group */
unsigned int numtriangles; /* number of triangles in this group */
unsigned int* triangles; /* array of triangle indices */
unsigned int material; /* index to material for group */
bool hastexcoords; /* set to true if triangles have texture coords */
struct GLMgroup* next; /* pointer to next group in model */
struct GLMgroup* next; /* pointer to next group in model */
void init()
{
name = NULL;
numtriangles = 0;
triangles = NULL;
material = 0;
name = NULL;
numtriangles = 0;
triangles = NULL;
material = 0;
hastexcoords = false;
next = NULL;
next = NULL;
}
};
/* GLMmodel: Structure that defines a model.
*/
struct GLMmodel {
char* pathname; /* path to this model */
char* mtllibname; /* name of the material library */
char* pathname; /* path to this model */
char* mtllibname; /* name of the material library */
unsigned int numvertices; /* number of vertices in model */
GLfloat* vertices; /* array of vertices */
unsigned int numvertices; /* number of vertices in model */
GLfloat* vertices; /* array of vertices */
unsigned int numnormals; /* number of normals in model */
GLfloat* normals; /* array of normals */
unsigned int numnormals; /* number of normals in model */
GLfloat* normals; /* array of normals */
unsigned int numtexcoords; /* number of texcoords in model */
GLfloat* texcoords; /* array of texture coordinates */
unsigned int numtexcoords; /* number of texcoords in model */
GLfloat* texcoords; /* array of texture coordinates */
unsigned int numfacetnorms; /* number of facetnorms in model */
GLfloat* facetnorms; /* array of facetnorms */
unsigned int numfacetnorms; /* number of facetnorms in model */
GLfloat* facetnorms; /* array of facetnorms */
unsigned int numtriangles; /* number of triangles in model */
GLMtriangle* triangles; /* array of triangles */
unsigned int numtriangles; /* number of triangles in model */
GLMtriangle* triangles; /* array of triangles */
unsigned int nummaterials; /* number of materials in model */
GLMmaterial* materials; /* array of materials */
unsigned int nummaterials; /* number of materials in model */
GLMmaterial* materials; /* array of materials */
unsigned int numgroups; /* number of groups in model */
GLMgroup* groups; /* linked list of groups */
unsigned int numgroups; /* number of groups in model */
GLMgroup* groups; /* linked list of groups */
GLfloat position[3]; /* position of the model */
GLfloat position[3]; /* position of the model */
void init()
{
pathname = NULL;
mtllibname = NULL;
pathname = NULL;
mtllibname = NULL;
numvertices = 0;
vertices = NULL;
numvertices = 0;
vertices = NULL;
numnormals = 0;
normals = NULL;
numnormals = 0;
normals = NULL;
numtexcoords = 0;
texcoords = NULL;
numtexcoords = 0;
texcoords = NULL;
numfacetnorms = 0;
facetnorms = NULL;
numfacetnorms = 0;
facetnorms = NULL;
numtriangles = 0;
triangles = NULL;
numtriangles = 0;
triangles = NULL;
nummaterials = 0;
materials = NULL;
nummaterials = 0;
materials = NULL;
numgroups = 0;
groups = NULL;
numgroups = 0;
groups = NULL;
position[0] = position[1] = position[2] = 0.0f;
position[0] = position[1] = position[2] = 0.0f;
}

View File

@ -103,7 +103,7 @@ bool Geometry_readLocalData(Object& obj, Input& fr)
{
// post 0.9.3 releases.
++fr;
Vec3Array* vertices = dynamic_cast<Vec3Array*>(Array_readLocalData(fr));
Array* vertices = Array_readLocalData(fr);
if (vertices)
{
geom.setVertexArray(vertices);

View File

@ -62,6 +62,14 @@ bool Text_readLocalData(osg::Object &obj, osgDB::Input &fr)
}
}
if (fr.matchSequence("characterSizeMode %w"))
{
std::string str = fr[1].getStr();
if (str=="OBJECT_COORDS") text.setCharacterSizeMode(osgText::Text::OBJECT_COORDS);
else if (str=="SCREEN_COORDS") text.setCharacterSizeMode(osgText::Text::SCREEN_COORDS);
else if (str=="OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT") text.setCharacterSizeMode(osgText::Text::OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT);
}
// maximum dimentsions of text box.
if (fr[0].matchWord("maximumWidth"))
{
@ -127,24 +135,6 @@ bool Text_readLocalData(osg::Object &obj, osgDB::Input &fr)
}
}
if (fr.matchSequence("scale %f"))
{
float scale;
fr[1].getFloat(scale);
text.setScale(scale);
fr += 2;
itAdvanced = true;
}
if (fr.matchSequence("autoUpdateEyeMovementTolerance %f"))
{
float scale;
fr[1].getFloat(scale);
text.setAutoUpdateEyeMovementTolerance(scale);
fr += 2;
itAdvanced = true;
}
if (fr.matchSequence("autoRotateToScreen TRUE"))
{
text.setAutoRotateToScreen(true);
@ -154,7 +144,7 @@ bool Text_readLocalData(osg::Object &obj, osgDB::Input &fr)
if (fr.matchSequence("autoScaleToLimitScreenSizeToFontResolution TRUE"))
{
text.setAutoScaleToLimitScreenSizeToFontResolution(true);
text.setCharacterSizeMode(osgText::Text::SCREEN_COORDS);
fr += 2;
itAdvanced = true;
}
@ -263,6 +253,14 @@ bool Text_writeLocalData(const osg::Object &obj, osgDB::Output &fw)
// charater size.
fw.indent() << "characterSize " << text.getCharacterHeight() << " " << text.getCharacterAspectRatio() << std::endl;
fw.indent() << "characterSizeMode ";
switch(text.getCharacterSizeMode())
{
case osgText::Text::OBJECT_COORDS : fw<<"OBJECT_COORDS"<<std::endl; break;
case osgText::Text::SCREEN_COORDS : fw<<"SCREEN_COORDS"<<std::endl; break;
case osgText::Text::OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT: fw<<"OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT"<<std::endl; break;
}
// maximum dimension of text box.
if (text.getMaximumWidth()>0.0f)
{
@ -301,25 +299,11 @@ bool Text_writeLocalData(const osg::Object &obj, osgDB::Output &fw)
fw.indent() << "rotation " << text.getRotation() << std::endl;
}
if (text.getScale()!=1.0f)
{
fw.indent() << "scale " << text.getScale() << std::endl;
}
if (text.getAutoUpdateEyeMovementTolerance()!=0.0f)
{
fw.indent() << "autoUpdateEyeMovementTolerance " << text.getAutoUpdateEyeMovementTolerance() << std::endl;
}
if (text.getAutoRotateToScreen())
{
fw.indent() << "autoRotateToScreen TRUE"<< std::endl;
}
if (text.getAutoScaleToLimitScreenSizeToFontResolution())
{
fw.indent() << "autoScaleToLimitScreenSizeToFontResolution TRUE"<< std::endl;
}
// layout
fw.indent() << "layout ";

View File

@ -28,6 +28,7 @@ TerrapageNode::~TerrapageNode()
{
// will the page manger delete the archive?
delete _pageManager;
_pageManager = 0L;
}
void TerrapageNode::traverse(osg::NodeVisitor& nv)

View File

@ -199,7 +199,7 @@ bool OSGPageManager::StartThread(ThreadMode mode,ThreadID &newThread)
DWORD dwThreadId=0;
LPVOID dwThrdParam = (LPVOID) this;
newThread = CreateThread(
threadID = newThread = CreateThread(
NULL, // default security attributes
0, // use default stack size
ThreadFunc, // thread function
@ -223,6 +223,7 @@ bool OSGPageManager::StartThread(ThreadMode mode,ThreadID &newThread)
threadMode = mode;
if( pthread_create( &newThread, 0L, ThreadFunc, (void *)this ) != 0 )
threadMode = ThreadNone;
threadID = newThread;
#endif
return threadMode != ThreadNone;
}
@ -232,10 +233,18 @@ bool OSGPageManager::StartThread(ThreadMode mode,ThreadID &newThread)
*/
bool OSGPageManager::EndThread()
{
cancel = true;
// claer the path for thred loop to finish
osgSetEvent(locationChangeEvent);
#ifdef _WIN32
DWORD res = STILL_ACTIVE;
while(res==STILL_ACTIVE){
GetExitCodeThread(threadID,&res);
Sleep(100);
}
#else
// Need a handle to the thread ID here.
//pthread_cancel( ?newThread? );
pthread_join( threadID, 0 );
#endif
return true;
}
@ -251,9 +260,10 @@ bool OSGPageManager::ThreadLoop()
if (threadMode != ThreadFree)
throw 1;
bool done = false;
bool pagingActive = false;
while (!done) {
cancel = false;
while (!cancel) {
/* Here's how we do it:
Wait for position change
Update manager w/ position
@ -308,36 +318,39 @@ bool OSGPageManager::ThreadLoop()
#endif
// Now do a single load
tile = pageManage->GetNextLoad();
osg::Group *tileGroup=NULL;
pagingActive = false;
if (tile) {
osg::Group *parentNode = NULL;
tileGroup = archive->LoadTile(NULL,pageManage,tile,&parentNode);
pageManage->AckLoad();
if (tileGroup) {
while( (tile = pageManage->GetNextLoad()) ) // Sasa's new code - more frame drops, but less missing tiles.
//if( (tile = pageManage->GetNextLoad()) ) // original code (0.9.4 and before) - less frame drops, more missing tiles.
{
osg::Group *tileGroup=NULL;
pagingActive = false;
osg::Group *parentNode = NULL;
tileGroup = archive->LoadTile(NULL,pageManage,tile,&parentNode);
pageManage->AckLoad();
if (tileGroup) {
#ifdef USE_THREADLOOP_DELETE
// Make an extra reference to it because we want it back for deletion
// RO, commenting out as we don't want to do delete here, we want it to happen in the merge thread.
tileGroup->ref();
// Make an extra reference to it because we want it back for deletion
// RO, commenting out as we don't want to do delete here, we want it to happen in the merge thread.
tileGroup->ref();
#endif
} else {
int x,y,lod;
tile->GetTileLoc(x,y,lod);
fprintf(stderr,"Failed to load tile (%d,%d,%d)\n",x,y,lod);
}
// Now add this tile to the merge list
if (tileGroup) {
osgLockMutex(changeListMutex);
toMerge.push_back(tileGroup);
toMergeParent.push_back(parentNode);
osgUnLockMutex(changeListMutex);
}
// We're not necessarily done paging, we're just handing control back
// It's likely we'll be back here
pagingActive = true;
}
}
else
{
int x,y,lod;
tile->GetTileLoc(x,y,lod);
fprintf(stderr,"Failed to load tile (%d,%d,%d)\n",x,y,lod);
}
// Now add this tile to the merge list
if (tileGroup) {
osgLockMutex(changeListMutex);
toMerge.push_back(tileGroup);
toMergeParent.push_back(parentNode);
osgUnLockMutex(changeListMutex);
}
// We're not necessarily done paging, we're just handing control back
// It's likely we'll be back here
pagingActive = true;
}
}
}

View File

@ -145,6 +145,8 @@ namespace txp
std::vector<osg::Group *> toMergeParent;
// Unhook list is filled in by the paging thread
std::vector<osg::Group *> toUnhook;
volatile bool cancel;
#ifdef USE_THREADLOOP_DELETE
// Main thread moves groups to the delete list as soon as they are unhooked

View File

@ -17,5 +17,12 @@ LIB = $(LIB_PREFIX)$(TARGET_BASENAME).$(LIB_EXT)
INC += $(PRODUCER_INCLUDE_DIR) -I/usr/X11R6/include
LDFLAGS += $(PRODUCER_LIB_DIR)
ifeq ($(USE_OPEN_THREAD),1)
DEF += -D_USE_OPEN_THREAD
INC += $(INC_OPEN_THREAD)
LDFLAGS += $(LIB_OPEN_THREAD)
LIBS += -lOpenThread
endif
include $(TOPDIR)/Make/makerules

View File

@ -187,24 +187,26 @@ void OsgCameraGroup::setUpSceneViewsWithData()
{
for(SceneHandlerList::iterator p = _shvec.begin(); p != _shvec.end(); p++ )
{
osgUtil::SceneView* sv = (*p)->getSceneView();
if (_scene_decorator.valid())
{
(*p)->setSceneData( _scene_decorator.get() );
sv->setSceneData( _scene_decorator.get() );
}
else if (_scene_data.valid())
{
(*p)->setSceneData( _scene_data.get() );
sv->setSceneData( _scene_data.get() );
}
else
{
(*p)->setSceneData( 0 );
sv->setSceneData( 0 );
}
(*p)->setFrameStamp( _frameStamp.get() );
(*p)->setGlobalStateSet( _global_stateset.get() );
(*p)->setBackgroundColor( _background_color );
(*p)->setLODScale( _LODScale );
(*p)->setFusionDistance( _fusionDistanceMode, _fusionDistanceValue );
sv->setFrameStamp( _frameStamp.get() );
sv->setGlobalStateSet( _global_stateset.get() );
sv->setBackgroundColor( _background_color );
sv->setLODScale( _LODScale );
sv->setFusionDistance( _fusionDistanceMode, _fusionDistanceValue );
}
}
@ -317,14 +319,17 @@ bool OsgCameraGroup::realize()
// create the scene handler.
osgProducer::OsgSceneHandler *sh = new osgProducer::OsgSceneHandler(_ds.get());
sh->setDefaults();
sh->getState()->setContextID(i);
osgUtil::SceneView* sv = sh->getSceneView();
sv->setDefaults();
sh->setContextID(i);
_shvec.push_back( sh );
cam->setSceneHandler( sh );
// set up the clear mask.
osgUtil::RenderStage *stage = sh->getRenderStage();
osgUtil::RenderStage *stage = sv->getRenderStage();
if (stage) stage->setClearMask(clear_mask);
// set the realize callback.
@ -363,7 +368,7 @@ bool OsgCameraGroup::realize()
if( _global_stateset == NULL && _shvec.size() > 0 )
{
SceneHandlerList::iterator p = _shvec.begin();
_global_stateset = (*p)->getGlobalStateSet();
_global_stateset = (*p)->getSceneView()->getGlobalStateSet();
}
setUpSceneViewsWithData();
@ -430,9 +435,9 @@ void OsgCameraGroup::setView(const osg::Matrix& matrix)
const osg::Matrix OsgCameraGroup::getViewMatrix() const
{
osg::Matrix matrix;
if (_cfg && _cfg->getNumberOfCameras()>=1)
if (_cfg.valid() && _cfg->getNumberOfCameras()>=1)
{
Producer::Camera *cam = _cfg->getCamera(0);
const Producer::Camera *cam = _cfg->getCamera(0);
matrix.set(cam->getViewMatrix());
}
return matrix;

View File

@ -18,10 +18,10 @@ using namespace osgUtil;
using namespace osgProducer;
OsgSceneHandler::OsgSceneHandler( osg::DisplaySettings *ds) :
osgUtil::SceneView(ds)
_sceneView(new osgUtil::SceneView(ds))
{
setProjectionMatrix( new osg::RefMatrix );
setModelViewMatrix( new osg::RefMatrix );
_sceneView->setProjectionMatrix( new osg::RefMatrix );
_sceneView->setModelViewMatrix( new osg::RefMatrix );
}
void OsgSceneHandler::init()
@ -31,7 +31,7 @@ void OsgSceneHandler::init()
mutex.lock();
osg::notify(osg::INFO)<<" running "<<this<<" init."<<std::endl;
SceneView::init();
_sceneView->SceneView::init();
osg::notify(osg::INFO)<<" done "<<this<<" init."<<std::endl;
mutex.unlock();
@ -46,24 +46,24 @@ void OsgSceneHandler::clearImplementation(Producer::Camera& /*camera*/)
void OsgSceneHandler::cullImplementation(Producer::Camera &cam)
{
getProjectionMatrix()->set(cam.getProjectionMatrix());
getModelViewMatrix()->set(cam.getPositionAndAttitudeMatrix());
_sceneView->getProjectionMatrix()->set(cam.getProjectionMatrix());
_sceneView->getModelViewMatrix()->set(cam.getPositionAndAttitudeMatrix());
int x, y;
unsigned int w, h;
cam.getProjectionRectangle( x, y, w, h );
setViewport( x, y, w, h );
_sceneView->setViewport( x, y, w, h );
SceneView::cull();
_sceneView->cull();
}
void OsgSceneHandler::drawImplementation(Producer::Camera &)
{
SceneView::draw();
_sceneView->SceneView::draw();
}
void OsgSceneHandler::setContextID( int id )
{
getState()->setContextID( id );
_sceneView->getState()->setContextID( id );
}

View File

@ -128,7 +128,7 @@ private:
// osgProducer::Viewer implemention
//
Viewer::Viewer():
_done(0),
_done(false),
_kbmcb(0),
_recordingAnimationPath(false)
{
@ -231,8 +231,8 @@ void Viewer::setUpViewer(unsigned int options)
}
if (!_updateVisitor) _updateVisitor = new osgUtil::UpdateVisitor;
_updateVisitor = new osgUtil::UpdateVisitor;
_updateVisitor->setFrameStamp(_frameStamp.get());
if (options&TRACKBALL_MANIPULATOR) addCameraManipulator(new osgGA::TrackballManipulator);
@ -320,7 +320,7 @@ bool Viewer::realize()
// draw traversal.
for(SceneHandlerList::iterator p=_shvec.begin(); p!=_shvec.end(); p++ )
{
(*p)->getState()->setAbortRenderingPtr(&_done);
(*p)->getSceneView()->getState()->setAbortRenderingPtr(&_done);
}
return _realized;
@ -433,11 +433,12 @@ bool Viewer::computeNearFarPoints(float x,float y,unsigned int cameraNum,osg::Ve
if (cameraNum>=getSceneHandlerList().size()) return false;
OsgSceneHandler* scenehandler = getSceneHandlerList()[cameraNum].get();
osgUtil::SceneView* sv = scenehandler->getSceneView();
float pixel_x,pixel_y;
if (computePixelCoords(x,y,cameraNum,pixel_x,pixel_y))
{
return scenehandler->projectWindowXYIntoObject((int)(pixel_x+0.5f),(int)(pixel_y+0.5f),near_point,far_point);
return sv->projectWindowXYIntoObject((int)(pixel_x+0.5f),(int)(pixel_y+0.5f),near_point,far_point);
}
return false;
@ -462,11 +463,12 @@ bool Viewer::computeIntersections(float x,float y,unsigned int cameraNum,osgUtil
//std::cout << " rx "<<rx<<" "<<ry<<std::endl;
osgProducer::OsgSceneHandler* sh = dynamic_cast<osgProducer::OsgSceneHandler*>(camera->getSceneHandler());
osgUtil::SceneView* sv = sh?sh->getSceneView():0;
osg::Matrix vum;
if (sh!=0 && sh->getModelViewMatrix()!=0 && sh->getProjectionMatrix()!=0)
if (sv!=0 && sv->getModelViewMatrix()!=0 && sv->getProjectionMatrix()!=0)
{
vum.set((*(sh->getModelViewMatrix())) *
(*(sh->getProjectionMatrix())));
vum.set((*(sv->getModelViewMatrix())) *
(*(sv->getProjectionMatrix())));
}
else
{

View File

@ -138,17 +138,18 @@ void ViewerEventHandler::StatsAndHelpDrawCallback::operator()( const Producer::C
_viewport->setViewport(x,y,width,height);
OsgSceneHandler* osh = _veh->getOsgCameraGroup()->getSceneHandlerList()[_cameraNumber].get();
osh->getState()->pushStateSet(_stateset.get());
osgUtil::SceneView* sv = osh->getSceneView();
sv->getState()->pushStateSet(_stateset.get());
if (_veh->getDisplayHelp()) displayHelp();
if (_veh->getFrameStatsMode()!=ViewerEventHandler::NO_STATS && camera.getInstrumentationMode())
{
osh->getState()->apply();
sv->getState()->apply();
displayStats();
}
osh->getState()->popStateSet();
sv->getState()->popStateSet();
}
@ -157,6 +158,7 @@ void ViewerEventHandler::StatsAndHelpDrawCallback::displayHelp()
if (!_helpInitialized) createHelpText();
OsgSceneHandler* osh = _veh->getOsgCameraGroup()->getSceneHandlerList()[_cameraNumber].get();
osgUtil::SceneView* sv = osh->getSceneView();
// should possibly update _viewport...
@ -180,21 +182,21 @@ void ViewerEventHandler::StatsAndHelpDrawCallback::displayHelp()
ditr!=_descriptionList.end();
++ditr)
{
(*ditr)->draw(*(osh->getState()));
(*ditr)->draw(*(sv->getState()));
}
for(TextList::iterator oitr=_optionList.begin();
oitr!=_optionList.end();
++oitr)
{
(*oitr)->draw(*(osh->getState()));
(*oitr)->draw(*(sv->getState()));
}
for(TextList::iterator eitr=_explanationList.begin();
eitr!=_explanationList.end();
++eitr)
{
(*eitr)->draw(*(osh->getState()));
(*eitr)->draw(*(sv->getState()));
}
@ -360,6 +362,7 @@ void ViewerEventHandler::StatsAndHelpDrawCallback::displayStats()
if (!_statsInitialized) createStatsText();
OsgSceneHandler* osh = _veh->getOsgCameraGroup()->getSceneHandlerList()[_cameraNumber].get();
osgUtil::SceneView* sv = osh->getSceneView();
// render the text
if (_veh->getFrameStatsMode()>=ViewerEventHandler::FRAME_RATE)
@ -384,7 +387,7 @@ void ViewerEventHandler::StatsAndHelpDrawCallback::displayStats()
char tmpText[128];
_frameRateLabelText->draw(*(osh->getState()));
_frameRateLabelText->draw(*(sv->getState()));
if (_fs.size()>1)
{
@ -394,7 +397,7 @@ void ViewerEventHandler::StatsAndHelpDrawCallback::displayStats()
sprintf(tmpText,"%4.2f",1.0/timePerFrame);
_frameRateCounterText->setText(tmpText);
}
_frameRateCounterText->draw(*(osh->getState()));
_frameRateCounterText->draw(*(sv->getState()));
if (_veh->getFrameStatsMode()>=ViewerEventHandler::CAMERA_STATS)
@ -405,7 +408,7 @@ void ViewerEventHandler::StatsAndHelpDrawCallback::displayStats()
itr!=_statsLabelList.end();
++itr)
{
(*itr)->draw(*(osh->getState()));
(*itr)->draw(*(sv->getState()));
}
double updateTime = 0.0;
@ -429,7 +432,7 @@ void ViewerEventHandler::StatsAndHelpDrawCallback::displayStats()
sprintf(tmpText,"%4.2f",1000.0*updateTime/(double)_fs.size());
_updateTimeText->setText(tmpText);
_updateTimeText->draw(*(osh->getState()));
_updateTimeText->draw(*(sv->getState()));
CameraTimes::iterator titr;
for(itr=_cullTimeText.begin(),titr = _cullTimes.begin();
@ -438,7 +441,7 @@ void ViewerEventHandler::StatsAndHelpDrawCallback::displayStats()
{
sprintf(tmpText,"%4.2f",1000.0*(*titr)/(double)_fs.size());
(*itr)->setText(tmpText);
(*itr)->draw(*(osh->getState()));
(*itr)->draw(*(sv->getState()));
}
for(itr=_drawTimeText.begin(),titr = _drawTimes.begin();
itr!=_drawTimeText.end() && titr!=_cullTimes.end();
@ -446,7 +449,7 @@ void ViewerEventHandler::StatsAndHelpDrawCallback::displayStats()
{
sprintf(tmpText,"%4.2f",1000.0*(*titr)/(double)_fs.size());
(*itr)->setText(tmpText);
(*itr)->draw(*(osh->getState()));
(*itr)->draw(*(sv->getState()));
}
}

View File

@ -10,6 +10,8 @@ CXXFILES = \
Sector.cpp\
Version.cpp\
# SphereSegment.cpp\
DEF += -DOSGSIM_LIBRARY
LIBS += -losg -losgUtil $(GL_LIBS) $(OTHER_LIBS)

View File

@ -41,7 +41,6 @@ LightPointDrawable::LightPointDrawable():
_colorMaskOff = new osg::ColorMask;
_colorMaskOff->setMask(false,false,false,false);
_point = new osg::Point;
}
LightPointDrawable::LightPointDrawable(const LightPointDrawable& lpd,const osg::CopyOp& copyop):

View File

@ -116,7 +116,6 @@ class OSGSIM_EXPORT LightPointDrawable : public osg::Drawable
osg::ref_ptr<osg::BlendFunc> _blendOne;
osg::ref_ptr<osg::BlendFunc> _blendOneMinusSrcAlpha;
osg::ref_ptr<osg::ColorMask> _colorMaskOff;
osg::ref_ptr<osg::Point> _point;
};

View File

@ -24,13 +24,29 @@
#include <typeinfo>
using namespace osgSim;
namespace osgSim
{
osg::StateSet* getSingletonLightPointStateSet()
{
static osg::ref_ptr<osg::StateSet> s_stateset = 0;
if (!s_stateset)
{
s_stateset = new osg::StateSet;
// force light point nodes to be drawn after everything else by picking a renderin bin number after
// the transparent bin.
s_stateset->setRenderBinDetails(20,"DepthSortedBin");
}
return s_stateset.get();
}
LightPointNode::LightPointNode():
_minPixelSize(0.0f),
_maxPixelSize(30.0f),
_maxVisableDistance2(FLT_MAX)
{
setStateSet(getSingletonLightPointStateSet());
}
/** Copy constructor using CopyOp to manage deep vs shallow copy.*/
@ -66,6 +82,12 @@ bool LightPointNode::computeBound() const
_bsphere.init();
_bbox.init();
if (_lightPointList.empty())
{
_bsphere_computed=true;
return false;
}
LightPointList::const_iterator itr;
for(itr=_lightPointList.begin();
@ -96,6 +118,12 @@ bool LightPointNode::computeBound() const
void LightPointNode::traverse(osg::NodeVisitor& nv)
{
if (_lightPointList.empty())
{
// no light points so no op.
return;
}
//#define USE_TIMER
#ifdef USE_TIMER
osg::Timer timer;
@ -363,3 +391,4 @@ void LightPointNode::traverse(osg::NodeVisitor& nv)
}
} // end of namespace

View File

@ -1,3 +1,4 @@
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
@ -459,22 +460,95 @@ void Font::GlyphTexture::apply(osg::State& state) const
}
static const GLubyte* s_renderer = 0;
static bool s_subloadAllGlyphsTogether = false;
if (!s_renderer)
{
s_renderer = glGetString(GL_RENDERER);
osg::notify(osg::INFO)<<"glGetString(GL_RENDERER)=="<<s_renderer<<std::endl;
if (strstr((const char*)s_renderer,"IMPACT")!=0)
{
// we're running on an Octane, so need to work around its
// subloading bugs by loading all at once.
s_subloadAllGlyphsTogether = true;
}
}
// now subload the glyphs that are outstanding for this graphics context.
GlyphPtrList& glyphsWereSubloading = _glyphsToSubload[contextID];
if (!glyphsWereSubloading.empty())
{
for(GlyphPtrList::iterator itr=glyphsWereSubloading.begin();
itr!=glyphsWereSubloading.end();
++itr)
if (!s_subloadAllGlyphsTogether)
{
(*itr)->subload();
// default way of subloading as required.
//std::cout<<"subloading"<<std::endl;
for(GlyphPtrList::iterator itr=glyphsWereSubloading.begin();
itr!=glyphsWereSubloading.end();
++itr)
{
(*itr)->subload();
}
// clear the list since we have now subloaded them.
glyphsWereSubloading.clear();
}
else
{
//std::cout<<"all loading"<<std::endl;
// Octane has bugs in OGL driver which mean that subloads smaller
// than 32x32 produce errors, and also cannot handle general alignment,
// so to get round this copy all glyphs into a temporary image and
// then subload the whole lot in one go.
int tsize = 2 * getTextureHeight() * getTextureWidth();
unsigned char *local_data = new unsigned char[tsize];
memset( local_data, 0L, tsize);
for(GlyphRefList::const_iterator itr=_glyphs.begin();
itr!=_glyphs.end();
++itr)
{
//(*itr)->subload();
// Rather than subloading to graphics, we'll write the values
// of the glyphs into some intermediate data and subload the
// whole thing at the end
for( int t = 0; t < (*itr)->t(); t++ )
{
for( int s = 0; s < (*itr)->s(); s++ )
{
int sindex = 2 * (t*(*itr)->s()+s);
int dindex = 2 *
((((*itr)->getTexturePositionY()+t) * getTextureWidth()) +
((*itr)->getTexturePositionX()+s));
const unsigned char *sptr = &(*itr)->data()[sindex];
unsigned char *dptr = &local_data[dindex];
(*dptr++) = (*sptr++);
(*dptr) = (*sptr);
}
}
}
// clear the list since we have now subloaded them.
glyphsWereSubloading.clear();
// Subload the image once
glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0,
getTextureWidth(),
getTextureHeight(),
GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, local_data );
delete [] local_data;
}
// clear the list since we have now subloaded them.
glyphsWereSubloading.clear();
}
else
{
@ -556,7 +630,7 @@ void Font::Glyph::subload() const
"\t "<<s()<<" ,"<<t()<<std::endl<<hex<<
"\t 0x"<<(GLenum)getPixelFormat()<<std::endl<<
"\t 0x"<<(GLenum)getDataType()<<std::endl<<
"\t 0x"<<(unsigned int)data()<<");"<<dec<<std::endl;
"\t 0x"<<(unsigned long)data()<<");"<<dec<<std::endl;
}
}

View File

@ -22,121 +22,22 @@
using namespace osgText;
struct TextCullCallback : public osg::Drawable::CullCallback
{
struct PositionData
{
PositionData():
_traversalNumber(-1),
_previousWidth(0),
_previousHeight(0) {}
int _traversalNumber;
int _previousWidth;
int _previousHeight;
osg::Vec3 _eyePosition;
};
TextCullCallback(osgText::Text* text):
_text(text) {}
/** do customized cull code.*/
virtual bool cull(osg::NodeVisitor *nv, osg::Drawable*, osg::State*) const
{
osgUtil::CullVisitor* cs = static_cast<osgUtil::CullVisitor*>(nv);
if (!cs) return false;
unsigned int contextID = cs->getState() ? cs->getState()->getContextID() : 0;
PositionData& positionData = _positions[contextID];
int width = positionData._previousWidth;
int height = positionData._previousHeight;
osg::Viewport* viewport = cs->getViewport();
if (viewport)
{
width = viewport->width();
height = viewport->height();
}
osg::Vec3 eyePoint = cs->getEyeLocal();
bool doUpdate = positionData._traversalNumber==-1;
if (positionData._traversalNumber>=0)
{
osg::Vec3 dv = positionData._eyePosition-eyePoint;
if (dv.length2()>_text->getAutoUpdateEyeMovementTolerance()*(eyePoint-_text->getPosition()).length2())
{
doUpdate = true;
}
else if (width!=positionData._previousWidth || height!=positionData._previousHeight)
{
doUpdate = true;
}
}
positionData._traversalNumber = nv->getTraversalNumber();
positionData._previousWidth = width;
positionData._previousHeight = height;
if (doUpdate)
{
float scale=_text->getScale(contextID);
if (_text->getAutoScaleToLimitScreenSizeToFontResolution())
{
float numPixels = cs->pixelSize(_text->getPosition(),_text->getCharacterHeight());
if (numPixels>_text->getFontHeight())
{
scale = _text->getFontHeight()/numPixels;
}
//float size = 1.0f/cs->pixelSize(_text->getPosition(),1.0f);
//_text->setScale(size);
}
osg::Quat rotation = _text->getRotation(contextID);
if (_text->getAutoRotateToScreen())
{
rotation.set(cs->getModelViewMatrix());
rotation = rotation.inverse();
}
_text->setScaleAndRotation(contextID,scale,rotation);
}
return false;
}
typedef osg::buffered_object<PositionData> PositionList;
mutable PositionList _positions;
mutable osgText::Text* _text;
};
Text::Text():
_fontWidth(32),
_fontHeight(32),
_characterHeight(32),
_characterAspectRatio(1.0f),
_characterSizeMode(OBJECT_COORDS),
_maximumWidth(0.0f),
_maximumHeight(0.0f),
_alignment(BASE_LINE),
_autoUpdateEyeMovementTolerance(0.0f),
_autoRotateToScreen(false),
_autoScaleToLimitScreenSizeToFontResolution(false),
_layout(LEFT_TO_RIGHT),
_color(1.0f,1.0f,1.0f,1.0f),
_drawMode(TEXT)
{
setUseDisplayList(false);
setScale(1.0f);
}
Text::Text(const Text& text,const osg::CopyOp& copyop):
@ -146,21 +47,18 @@ Text::Text(const Text& text,const osg::CopyOp& copyop):
_fontHeight(text._fontHeight),
_characterHeight(text._characterHeight),
_characterAspectRatio(text._characterAspectRatio),
_characterSizeMode(text._characterSizeMode),
_maximumWidth(text._maximumWidth),
_maximumHeight(text._maximumHeight),
_text(text._text),
_position(text._position),
_alignment(text._alignment),
_rotation(text._rotation),
_scale(text._scale),
_autoUpdateEyeMovementTolerance(text._autoUpdateEyeMovementTolerance),
_autoRotateToScreen(text._autoRotateToScreen),
_autoScaleToLimitScreenSizeToFontResolution(text._autoScaleToLimitScreenSizeToFontResolution),
_layout(text._layout),
_color(text._color),
_drawMode(text._drawMode)
{
setUpAutoCallback();
computeGlyphRepresentation();
}
@ -189,7 +87,6 @@ void Text::setFontResolution(unsigned int width, unsigned int height)
computeGlyphRepresentation();
}
void Text::setCharacterSize(float height,float aspectRatio)
{
_characterHeight = height;
@ -278,75 +175,19 @@ void Text::setAxisAlignment(AxisAlignment axis)
void Text::setRotation(const osg::Quat& quat)
{
for(unsigned int i=0;i<_rotation.size();++i)
{
setRotation(i,quat);
}
_rotation = quat;
computePositions();
}
void Text::setRotation(unsigned int contextID, const osg::Quat& quat)
{
if (_rotation[contextID]==quat) return;
_rotation[contextID] = quat;
computePositions(contextID);
}
void Text::setScale(float scale)
{
for(unsigned int i=0;i<_scale.size();++i)
{
setScale(i,scale);
}
}
void Text::setScale(unsigned int contextID, float scale)
{
if (_scale[contextID]==scale) return;
_scale[contextID] = scale;
computePositions(contextID);
}
void Text::setScaleAndRotation(unsigned int contextID, float scale,const osg::Quat& quat)
{
if (_scale[contextID]==scale && _rotation[contextID]==quat) return;
_scale[contextID] = scale;
_rotation[contextID] = quat;
computePositions(contextID);
}
void Text::setAutoScaleToLimitScreenSizeToFontResolution(bool autoScaleToScreen)
{
if (_autoScaleToLimitScreenSizeToFontResolution==autoScaleToScreen) return;
_autoScaleToLimitScreenSizeToFontResolution = autoScaleToScreen;
setUpAutoCallback();
}
void Text::setAutoRotateToScreen(bool autoRotateToScreen)
{
if (_autoRotateToScreen==autoRotateToScreen) return;
_autoRotateToScreen = autoRotateToScreen;
setUpAutoCallback();
}
void Text::setUpAutoCallback()
{
if (_autoRotateToScreen || _autoScaleToLimitScreenSizeToFontResolution)
{
if (!getCullCallback())
{
setCullCallback(new TextCullCallback(this));
}
}
else setCullCallback(0);
}
void Text::setLayout(Layout layout)
{
if (_layout==layout) return;
@ -369,7 +210,7 @@ void Text::setDrawMode(unsigned int mode)
_drawMode=mode;
if (_drawMode&TEXT_PIXMAP)
{
setAutoScaleToLimitScreenSizeToFontResolution(true);
setCharacterSizeMode(SCREEN_COORDS);
setAutoRotateToScreen(true);
}
computeGlyphRepresentation();
@ -388,9 +229,9 @@ bool Text::computeBound() const
if (_textBB.valid())
{
for(unsigned int i=0;i<_matrix.size();++i)
for(unsigned int i=0;i<_autoTransformCache.size();++i)
{
osg::Matrix& matrix = _matrix[i];
osg::Matrix& matrix = _autoTransformCache[i]._matrix;
_bbox.expandBy(osg::Vec3(_textBB.xMin(),_textBB.yMin(),_textBB.zMin())*matrix);
_bbox.expandBy(osg::Vec3(_textBB.xMax(),_textBB.yMin(),_textBB.zMin())*matrix);
_bbox.expandBy(osg::Vec3(_textBB.xMax(),_textBB.yMax(),_textBB.zMin())*matrix);
@ -605,13 +446,13 @@ void Text::computeGlyphRepresentation()
void Text::computePositions()
{
for(unsigned int i=0;i<_matrix.size();++i)
for(unsigned int i=0;i<_autoTransformCache.size();++i)
{
computePositions(i);
}
}
void Text::computePositions(unsigned int contextID)
void Text::computePositions(unsigned int contextID) const
{
switch(_alignment)
@ -632,18 +473,92 @@ void Text::computePositions(unsigned int contextID)
case RIGHT_BASE_LINE: _offset.set((_textBB.xMax()+_textBB.xMin()),0.0f,0.0f); break;
}
osg::Matrix& matrix = _matrix[contextID];
AutoTransformCache& atc = _autoTransformCache[contextID];
osg::Matrix& matrix = atc._matrix;
if (_scale[contextID]!=1.0f || !_rotation[contextID].zeroRotation())
if (_characterSizeMode!=OBJECT_COORDS || _autoRotateToScreen)
{
matrix.makeTranslate(-_offset);
if (_scale[contextID]!=1.0f)
matrix.postMult(osg::Matrix::scale(_scale[contextID],_scale[contextID],_scale[contextID]));
if (!_rotation[contextID].zeroRotation())
matrix.postMult(osg::Matrix::rotate(_rotation[contextID]));
osg::Matrix rotate_matrix;
if (_autoRotateToScreen)
{
osg::Vec3 trans(atc._modelview.getTrans());
atc._modelview.setTrans(0.0f,0.0f,0.0f);
rotate_matrix.invert(atc._modelview);
atc._modelview.setTrans(trans);
}
if (_characterSizeMode!=OBJECT_COORDS)
{
osg::Matrix M(rotate_matrix*osg::Matrix::translate(_position)*atc._modelview);
osg::Matrix& P = atc._projection;
// compute the pixel size vector.
// pre adjust P00,P20,P23,P33 by multiplying them by the viewport window matrix.
// here we do it in short hand with the knowledge of how the window matrix is formed
// note P23,P33 are multiplied by an implicit 1 which would come from the window matrix.
// Robert Osfield, June 2002.
// scaling for horizontal pixels
float P00 = P(0,0)*atc._width*0.5f;
float P20_00 = P(2,0)*atc._width*0.5f + P(2,3)*atc._width*0.5f;
osg::Vec3 scale_00(M(0,0)*P00 + M(0,2)*P20_00,
M(1,0)*P00 + M(1,2)*P20_00,
M(2,0)*P00 + M(2,2)*P20_00);
// scaling for vertical pixels
float P10 = P(1,1)*atc._height*0.5f;
float P20_10 = P(2,1)*atc._height*0.5f + P(2,3)*atc._height*0.5f;
osg::Vec3 scale_10(M(0,1)*P10 + M(0,2)*P20_10,
M(1,1)*P10 + M(1,2)*P20_10,
M(2,1)*P10 + M(2,2)*P20_10);
float P23 = P(2,3);
float P33 = P(3,3);
float pixelSizeVector_w = M(3,2)*P23 + M(3,3)*P33;
float pixelSize = (_characterHeight*sqrtf(scale_00.length2()+scale_10.length2()))/(pixelSizeVector_w*0.701f);
if (_characterSizeMode==SCREEN_COORDS)
{
float scale_font = _characterHeight/pixelSize;
matrix.postMult(osg::Matrix::scale(scale_font, scale_font,1.0f));
}
else if (pixelSize>_fontHeight)
{
float scale_font = _fontHeight/pixelSize;
matrix.postMult(osg::Matrix::scale(scale_font, scale_font,1.0f));
}
}
if (_autoRotateToScreen)
{
matrix.postMult(rotate_matrix);
}
if (!_rotation.zeroRotation() )
{
matrix.postMult(osg::Matrix::rotate(_rotation));
}
matrix.postMult(osg::Matrix::translate(_position));
}
else if (!_rotation.zeroRotation())
{
matrix.makeTranslate(-_offset);
matrix.postMult(osg::Matrix::rotate(_rotation));
matrix.postMult(osg::Matrix::translate(_position));
}
else
@ -651,6 +566,7 @@ void Text::computePositions(unsigned int contextID)
matrix.makeTranslate(_position-_offset);
}
// now apply matrix to the glyphs.
for(TextureGlyphQuadMap::iterator titr=_textureGlyphQuadMap.begin();
@ -676,13 +592,60 @@ void Text::computePositions(unsigned int contextID)
_normal = osg::Matrix::transform3x3(osg::Vec3(0.0f,0.0f,1.0f),matrix);
_normal.normalize();
dirtyBound();
const_cast<Text*>(this)->dirtyBound();
}
void Text::drawImplementation(osg::State& state) const
{
unsigned int contextID = state.getContextID();
if (_characterSizeMode!=OBJECT_COORDS || _autoRotateToScreen)
{
int frameNumber = state.getFrameStamp()?state.getFrameStamp()->getFrameNumber():0;
AutoTransformCache& atc = _autoTransformCache[contextID];
const osg::Matrix& modelview = state.getModelViewMatrix();
osg::Vec3 newTransformedPosition = _position*modelview;
int width = atc._width;
int height = atc._height;
const osg::Viewport* viewport = state.getCurrentViewport();
if (viewport)
{
width = viewport->width();
height = viewport->height();
}
bool doUpdate = atc._traversalNumber==-1;
if (atc._traversalNumber>=0)
{
if (atc._modelview!=modelview)
{
doUpdate = true;
}
else if (width!=atc._width || height!=atc._height)
{
doUpdate = true;
}
}
atc._traversalNumber = frameNumber;
atc._width = width;
atc._height = height;
if (doUpdate)
{
atc._transformedPosition = newTransformedPosition;
atc._projection = state.getProjectionMatrix();
atc._modelview = modelview;
computePositions(contextID);
}
}
glNormal3fv(_normal.ptr());
glColor4fv(_color.ptr());
@ -745,7 +708,7 @@ void Text::drawImplementation(osg::State& state) const
{
state.applyTextureMode(0,GL_TEXTURE_2D,osg::StateAttribute::OFF);
osg::Matrix& matrix = _matrix[contextID];
const osg::Matrix& matrix = _autoTransformCache[contextID]._matrix;
osg::Vec3 c00(osg::Vec3(_textBB.xMin(),_textBB.yMin(),_textBB.zMin())*matrix);
osg::Vec3 c10(osg::Vec3(_textBB.xMax(),_textBB.yMin(),_textBB.zMin())*matrix);
@ -767,9 +730,9 @@ void Text::drawImplementation(osg::State& state) const
{
glColor4f(1.0f,0.0f,1.0f,1.0f);
float cursorsize = _characterHeight*0.5f*_scale[contextID];
float cursorsize = _characterHeight*0.5f;
osg::Matrix& matrix = _matrix[contextID];
const osg::Matrix& matrix = _autoTransformCache[contextID]._matrix;
osg::Vec3 hl(osg::Vec3(_offset.x()-cursorsize,_offset.y(),_offset.z())*matrix);
osg::Vec3 hr(osg::Vec3(_offset.x()+cursorsize,_offset.y(),_offset.z())*matrix);
@ -814,14 +777,6 @@ void Text::accept(osg::Drawable::PrimitiveFunctor& pf) const
pf.setVertexArray(glyphquad._transformedCoords[0].size(),&(glyphquad._transformedCoords[0].front()));
pf.drawArrays(GL_QUADS,0,glyphquad._transformedCoords[0].size());
// pf.begin(GL_QUADS);
// for(GlyphQuads::Coords3::const_iterator itr = glyphquad._transformedCoords.begin();
// itr!=glyphquad._transformedCoords.end();
// ++itr)
// {
// pf.vertex(*itr);
// }
// pf.end();
}
}

View File

@ -524,7 +524,7 @@ bool IntersectVisitor::intersect(Drawable& drawable)
if (geometry)
{
osg::Vec3Array* vertices = geometry->getVertexArray();
osg::Vec3Array* vertices = dynamic_cast<osg::Vec3Array*>(geometry->getVertexArray());
if (vertices)
{
osg::Vec3* first = &(vertices->front());

View File

@ -13,6 +13,7 @@
#include <osgUtil/Optimizer>
#include <osg/Transform>
#include <osg/TransformAttributeFunctor>
#include <osg/MatrixTransform>
#include <osg/PositionAttitudeTransform>
#include <osg/LOD>
@ -106,45 +107,6 @@ void Optimizer::optimize(osg::Node* node, unsigned int options)
}
class TransformFunctor : public osg::Drawable::AttributeFunctor
{
public:
osg::Matrix _m;
osg::Matrix _im;
TransformFunctor(const osg::Matrix& m)
{
_m = m;
_im.invert(_m);
}
virtual ~TransformFunctor() {}
virtual void apply(osg::Drawable::AttributeType type,unsigned int count,osg::Vec3* begin)
{
if (type == osg::Drawable::VERTICES)
{
osg::Vec3* end = begin+count;
for (osg::Vec3* itr=begin;itr<end;++itr)
{
(*itr) = (*itr)*_m;
}
}
else if (type == osg::Drawable::NORMALS)
{
osg::Vec3* end = begin+count;
for (osg::Vec3* itr=begin;itr<end;++itr)
{
// note post mult by inverse for normals.
(*itr) = osg::Matrix::transform3x3(_im,(*itr));
(*itr).normalize();
}
}
}
};
////////////////////////////////////////////////////////////////////////////
// Optimize State Visitor
@ -535,7 +497,7 @@ void CollectLowestTransformsVisitor::doTransform(osg::Object* obj,osg::Matrix& m
osg::Drawable* drawable = dynamic_cast<osg::Drawable*>(obj);
if (drawable)
{
TransformFunctor tf(matrix);
osg::TransformAttributeFunctor tf(matrix);
drawable->accept(tf);
drawable->dirtyBound();
return;
@ -570,7 +532,7 @@ void CollectLowestTransformsVisitor::doTransform(osg::Object* obj,osg::Matrix& m
osg::Matrix matrix_no_trans = matrix;
matrix_no_trans.setTrans(0.0f,0.0f,0.0f);
TransformFunctor tf(matrix_no_trans);
osg::TransformAttributeFunctor tf(matrix_no_trans);
osg::Vec3 axis = osg::Matrix::transform3x3(tf._im,billboard->getAxis());
axis.normalize();
@ -1362,14 +1324,62 @@ bool Optimizer::MergeGeometryVisitor::geometryContainsSharedArrays(osg::Geometry
return false;
}
class MergeArrayVisitor : public osg::ArrayVisitor
{
public:
osg::Array* _lhs;
MergeArrayVisitor() :
_lhs(0) {}
void merge(osg::Array* lhs,osg::Array* rhs)
{
if (lhs==0 || rhs==0) return;
if (lhs->getType()!=rhs->getType()) return;
_lhs = lhs;
rhs->accept(*this);
}
template<typename T>
void _merge(T& rhs)
{
T* lhs = static_cast<T*>(_lhs);
lhs->insert(lhs->end(),rhs.begin(),rhs.end());
}
virtual void apply(osg::Array&) { osg::notify(osg::WARN) << "Warning: Optimizer's MergeArrayVisitor cannot merge Array type." << std::endl; }
virtual void apply(osg::ByteArray& rhs) { _merge(rhs); }
virtual void apply(osg::ShortArray& rhs) { _merge(rhs); }
virtual void apply(osg::IntArray& rhs) { _merge(rhs); }
virtual void apply(osg::UByteArray& rhs) { _merge(rhs); }
virtual void apply(osg::UShortArray& rhs) { _merge(rhs); }
virtual void apply(osg::UIntArray& rhs) { _merge(rhs); }
virtual void apply(osg::UByte4Array& rhs) { _merge(rhs); }
virtual void apply(osg::FloatArray& rhs) { _merge(rhs); }
virtual void apply(osg::Vec2Array& rhs) { _merge(rhs); }
virtual void apply(osg::Vec3Array& rhs) { _merge(rhs); }
virtual void apply(osg::Vec4Array& rhs) { _merge(rhs); }
};
bool Optimizer::MergeGeometryVisitor::mergeGeometry(osg::Geometry& lhs,osg::Geometry& rhs)
{
MergeArrayVisitor merger;
unsigned int base = 0;
if (lhs.getVertexArray() && rhs.getVertexArray())
{
base = lhs.getVertexArray()->size();
lhs.getVertexArray()->insert(lhs.getVertexArray()->end(),rhs.getVertexArray()->begin(),rhs.getVertexArray()->end());
base = lhs.getVertexArray()->getNumElements();
merger.merge(lhs.getVertexArray(),rhs.getVertexArray());
}
else if (rhs.getVertexArray())
{
@ -1378,7 +1388,7 @@ bool Optimizer::MergeGeometryVisitor::mergeGeometry(osg::Geometry& lhs,osg::Geom
if (lhs.getNormalArray() && rhs.getNormalArray() && lhs.getNormalBinding()!=osg::Geometry::BIND_OVERALL)
{
lhs.getNormalArray()->insert(lhs.getNormalArray()->end(),rhs.getNormalArray()->begin(),rhs.getNormalArray()->end());
merger.merge(lhs.getNormalArray(),rhs.getNormalArray());
}
else if (rhs.getNormalArray())
{
@ -1387,34 +1397,34 @@ bool Optimizer::MergeGeometryVisitor::mergeGeometry(osg::Geometry& lhs,osg::Geom
if (lhs.getColorArray() && rhs.getColorArray() && lhs.getColorBinding()!=osg::Geometry::BIND_OVERALL)
{
// we need to add the handling of the other array types...
osg::Vec4Array* col_lhs = dynamic_cast<osg::Vec4Array*>(lhs.getColorArray());
osg::Vec4Array* col_rhs = dynamic_cast<osg::Vec4Array*>(rhs.getColorArray());
if (col_lhs && col_rhs)
{
col_lhs->insert(col_lhs->end(),col_rhs->begin(),col_rhs->end());
}
merger.merge(lhs.getColorArray(),rhs.getColorArray());
}
else if (rhs.getColorArray())
{
lhs.setColorArray(rhs.getColorArray());
}
// need to implement handle secondary color array.
if (lhs.getSecondaryColorArray() && rhs.getSecondaryColorArray() && lhs.getSecondaryColorBinding()!=osg::Geometry::BIND_OVERALL)
{
merger.merge(lhs.getSecondaryColorArray(),rhs.getSecondaryColorArray());
}
else if (rhs.getColorArray())
{
lhs.setSecondaryColorArray(rhs.getSecondaryColorArray());
}
// need to implement handle fog coord array.
if (lhs.getFogCoordArray() && rhs.getFogCoordArray() && lhs.getFogCoordBinding()!=osg::Geometry::BIND_OVERALL)
{
merger.merge(lhs.getFogCoordArray(),rhs.getFogCoordArray());
}
else if (rhs.getColorArray())
{
lhs.setFogCoordArray(rhs.getFogCoordArray());
}
for(unsigned int unit=0;unit<lhs.getNumTexCoordArrays();++unit)
{
// we need to add the handling of the other array types...
osg::Vec2Array* tex_lhs = dynamic_cast<osg::Vec2Array*>(lhs.getTexCoordArray(unit));
osg::Vec2Array* tex_rhs = dynamic_cast<osg::Vec2Array*>(rhs.getTexCoordArray(unit));
if (tex_lhs && tex_rhs)
{
tex_lhs->insert(tex_lhs->end(),tex_rhs->begin(),tex_rhs->end());
}
merger.merge(lhs.getTexCoordArray(unit),rhs.getTexCoordArray(unit));
}
// shift the indices of the incomming primitives to account for the pre exisiting geometry.

View File

@ -65,6 +65,16 @@ SceneView::~SceneView()
void SceneView::setDefaults()
{
if (!_projectionMatrix)
{
_projectionMatrix = new RefMatrix();
_projectionMatrix->makePerspective(50.0f,1.4f,1.0f,10000.0f);
}
if (!_modelviewMatrix)
{
_modelviewMatrix = new RefMatrix();
}
_globalStateSet = new osg::StateSet;
_lightingMode=HEADLIGHT;

View File

@ -109,7 +109,7 @@ void SmoothingVisitor::smooth(osg::Geometry& geom)
if (!numSurfacePrimitives) return;
osg::Vec3Array *coords = geom.getVertexArray();
osg::Vec3Array *coords = dynamic_cast<osg::Vec3Array*>(geom.getVertexArray());
if (!coords || !coords->size()) return;
osg::Vec3Array *normals = new osg::Vec3Array(coords->size());

View File

@ -149,7 +149,7 @@ class InsertNewVertices : public osg::ArrayVisitor
void Tesselator::retesselatePolygons(osg::Geometry& geom)
{
Vec3Array* vertices = geom.getVertexArray();
osg::Vec3Array* vertices = dynamic_cast<osg::Vec3Array*>(geom.getVertexArray());
if (!vertices || vertices->empty() || geom.getPrimitiveSetList().empty()) return;