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

View File

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

View File

@ -23,7 +23,7 @@ print_pkginfo()
PKG="$1" PKG="$1"
NAME="$2" NAME="$2"
`[ "$OS" = "SunOS" ] && echo ARCH=sparc` `[ "$OS" = "SunOS" ] && echo ARCH=sparc`
VERSION=`$TOPDIR/bin/osgversion` VERSION=`gmake -s version`
CATEGORY="application,graphics,opengl" CATEGORY="application,graphics,opengl"
DESC="$3" DESC="$3"
BASEDIR="/opt/" BASEDIR="/opt/"
@ -67,7 +67,7 @@ make_installable()
{ {
PKGNAME=$1 PKGNAME=$1
PKGDIR=$PKGNAME.pkg PKGDIR=$PKGNAME.pkg
DISTNAME="$PKGNAME"-"`$TOPDIR/bin/osgversion`"-"$OS".shar DISTNAME="$PKGNAME"-"`gmake -s version`"-"$OS".shar
THISDIR=`pwd` THISDIR=`pwd`
cd $PKGSUBDIR 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> Project: "Example osgreflect"=.\examples\osgreflect\osgreflect.dsp - Package Owner=<4>
Package=<5> Package=<5>

View File

@ -421,6 +421,10 @@ SOURCE=..\..\src\osg\Transform.cpp
# End Source File # End Source File
# Begin Source File # Begin Source File
SOURCE=..\..\src\osg\TransformAttributeFunctor.cpp
# End Source File
# Begin Source File
SOURCE=..\..\src\osg\BlendFunc.cpp SOURCE=..\..\src\osg\BlendFunc.cpp
# End Source File # End Source File
# Begin Source File # Begin Source File
@ -837,6 +841,11 @@ SOURCE=..\..\Include\Osg\Transform
# End Source File # End Source File
# Begin Source File # Begin Source File
SOURCE=..\..\Include\Osg\TransformAttributeFunctor
# End Source File
# Begin Source File
SOURCE=..\..\Include\Osg\TriangleFunctor SOURCE=..\..\Include\Osg\TriangleFunctor
# End Source File # End Source File
# Begin 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 INC += $(PRODUCER_INCLUDE_DIR) -I/usr/X11R6/include -I/usr/X11R6/include
LDFLAGS += $(PRODUCER_LIB_DIR) -L/usr/X11R6/lib 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 include $(TOPDIR)/Make/makerules

View File

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

View File

@ -9,6 +9,8 @@
#include <osgDB/WriteFile> #include <osgDB/WriteFile>
#include <osgDB/ReaderWriter> #include <osgDB/ReaderWriter>
#include <osgUtil/Optimizer>
#include "OrientationConverter.h" #include "OrientationConverter.h"
#include "GeoSet.h" #include "GeoSet.h"
@ -273,6 +275,10 @@ int main( int argc, char **argv )
ConvertGeoSetsToGeometryVisitor cgtg; ConvertGeoSetsToGeometryVisitor cgtg;
root->accept(cgtg); root->accept(cgtg);
// optimize the scene graph, remove rendundent nodes and state etc.
osgUtil::Optimizer optimizer;
optimizer.optimize(root.get());
if( do_convert ) if( do_convert )
root = oc.convert( root.get() ); 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. // turn lighting off for the text and disable depth test to ensure its always ontop.
osg::StateSet* stateset = geode->getOrCreateStateSet(); osg::StateSet* stateset = geode->getOrCreateStateSet();
stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF); 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)); 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 position(150.0f,800.0f,0.0f);
osg::Vec3 delta(0.0f,-120.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) ++itr)
{ {
// switch off small feature culling to prevent the light points from being culled. // 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); 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!=viewer.getSceneHandlerList().end();
++itr) ++itr)
{ {
osgUtil::SceneView* sceneview = itr->get(); osgUtil::SceneView* sceneview = (*itr)->getSceneView();
sceneview->setCullMask(0xffffffff); sceneview->setCullMask(0xffffffff);
sceneview->setCullMaskLeft(0x00000001); sceneview->setCullMaskLeft(0x00000001);
sceneview->setCullMaskRight(0x00000002); sceneview->setCullMaskRight(0x00000002);

View File

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

View File

@ -13,6 +13,43 @@
#include <osgUtil/Optimizer> #include <osgUtil/Optimizer>
#include <osgProducer/Viewer> #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 ) int main( int argc, char **argv )
{ {

View File

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

View File

@ -340,7 +340,9 @@ class SG_EXPORT Drawable : public Object
virtual ~PrimitiveFunctor() {} 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 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 drawArrays(GLenum mode,GLint first,GLsizei count) = 0;
virtual void drawElements(GLenum mode,GLsizei count,const GLubyte* indices) = 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 drawElements(GLenum mode,GLsizei count,const GLuint* indices) = 0;
virtual void begin(GLenum mode) = 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 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) = 0;
virtual void vertex(float x,float y,float z,float w) = 0;
virtual void end() = 0; virtual void end() = 0;
}; };

View File

@ -51,9 +51,9 @@ class SG_EXPORT Geometry : public Drawable
BIND_PER_VERTEX BIND_PER_VERTEX
}; };
void setVertexArray(Vec3Array* array) { _vertexArray = array; dirtyDisplayList(); dirtyBound(); } void setVertexArray(Array* array) { _vertexArray = array; dirtyDisplayList(); dirtyBound(); }
Vec3Array* getVertexArray() { return _vertexArray.get(); } Array* getVertexArray() { return _vertexArray.get(); }
const Vec3Array* getVertexArray() const { return _vertexArray.get(); } const Array* getVertexArray() const { return _vertexArray.get(); }
void setVertexIndices(IndexArray* array) { _vertexIndices = array; _fastPathComputed=false; dirtyDisplayList(); dirtyBound(); } void setVertexIndices(IndexArray* array) { _vertexIndices = array; _fastPathComputed=false; dirtyDisplayList(); dirtyBound(); }
IndexArray* getVertexIndices() { return _vertexIndices.get(); } IndexArray* getVertexIndices() { return _vertexIndices.get(); }
@ -366,7 +366,7 @@ class SG_EXPORT Geometry : public Drawable
#ifdef COMPILE_POSSIBLE_NEW_ARRAY_METHODS #ifdef COMPILE_POSSIBLE_NEW_ARRAY_METHODS
AttributeList _attributeList; AttributeList _attributeList;
#endif #endif
ref_ptr<Vec3Array> _vertexArray; ref_ptr<Array> _vertexArray;
ref_ptr<IndexArray> _vertexIndices; ref_ptr<IndexArray> _vertexIndices;
mutable AttributeBinding _normalBinding; mutable AttributeBinding _normalBinding;

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.*/ /** return the numbers of bytes the whole row/image/volume of pixels occupies.*/
inline unsigned int getTotalSizeInBytes() const { return getImageSizeInBytes()*_r; } 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.*/ /** raw image data.*/
inline unsigned char *data() { return _data; } inline unsigned char *data() { return _data; }

View File

@ -113,6 +113,12 @@ const double PI_4 = 0.78539816339744830962;
template<typename T> template<typename T>
inline T absolute(T v) { return v<(T)0?-v:v; } 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. /** return the minimum of two values, equivilant to std::min.
* std::min not used because of STL implementation under IRIX contains no std::min.*/ * std::min not used because of STL implementation under IRIX contains no std::min.*/
template<typename T> template<typename T>

View File

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

View File

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

View File

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

View File

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

View File

@ -106,11 +106,11 @@ public:
virtual bool removeChild(GUIEventHandler *geh); 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 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; } 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;} SceneHandlerList& getSceneHandlerList() { return _shvec;}

View File

@ -22,12 +22,21 @@
namespace osgProducer { namespace osgProducer {
class OSGPRODUCER_EXPORT OsgSceneHandler : public Producer::Camera::SceneHandler, public osgUtil::SceneView class OSGPRODUCER_EXPORT OsgSceneHandler : public Producer::Camera::SceneHandler
{ {
public : public :
OsgSceneHandler(osg::DisplaySettings *ds = NULL); 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. /// override the init method to force it be run one at a time.
virtual void init(); virtual void init();
@ -85,6 +94,9 @@ class OSGPRODUCER_EXPORT OsgSceneHandler : public Producer::Camera::SceneHandler
virtual ~OsgSceneHandler() {} virtual ~OsgSceneHandler() {}
osg::ref_ptr<osgUtil::SceneView> _sceneView;
osg::ref_ptr<Callback> _clearCallback; osg::ref_ptr<Callback> _clearCallback;
osg::ref_ptr<Callback> _cullCallback; osg::ref_ptr<Callback> _cullCallback;
osg::ref_ptr<Callback> _drawCallback; osg::ref_ptr<Callback> _drawCallback;

View File

@ -82,8 +82,19 @@ class OSGPRODUCER_EXPORT Viewer : public OsgCameraGroup, public osgGA::GUIAction
virtual bool realize(); 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(); 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.*/ /** Dispatch the cull and draw for each of the Camera's for this frame.*/
virtual void frame(); virtual void frame();

View File

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

View File

@ -100,6 +100,18 @@ public:
float getCharacterHeight() const { return _characterHeight; } float getCharacterHeight() const { return _characterHeight; }
float getCharacterAspectRatio() const { return _characterAspectRatio; } 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. /** Set the maximum width of the text box.
@ -165,27 +177,11 @@ public:
void setAxisAlignment(AxisAlignment axis); void setAxisAlignment(AxisAlignment axis);
void setRotation(const osg::Quat& quat); void setRotation(const osg::Quat& quat);
void setRotation(unsigned int contextID, const osg::Quat& quat); const osg::Quat& getRotation() const { return _rotation; }
const osg::Quat& getRotation(unsigned int contextID=0) const { return _rotation[contextID]; }
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); void setAutoRotateToScreen(bool autoRotateToScreen);
bool getAutoRotateToScreen() const { return _autoRotateToScreen; } bool getAutoRotateToScreen() const { return _autoRotateToScreen; }
void setAutoScaleToLimitScreenSizeToFontResolution(bool autoScaleToScreen);
bool getAutoScaleToLimitScreenSizeToFontResolution() const { return _autoScaleToLimitScreenSizeToFontResolution; }
enum Layout enum Layout
{ {
LEFT_TO_RIGHT, /// default LEFT_TO_RIGHT, /// default
@ -295,35 +291,49 @@ protected:
unsigned int _fontHeight; unsigned int _fontHeight;
float _characterHeight; float _characterHeight;
float _characterAspectRatio; float _characterAspectRatio;
CharacterSizeMode _characterSizeMode;
float _maximumWidth; float _maximumWidth;
float _maximumHeight; float _maximumHeight;
String _text; String _text;
osg::Vec3 _position; osg::Vec3 _position;
AlignmentType _alignment; AlignmentType _alignment;
mutable osg::buffered_object<osg::Quat> _rotation; osg::Quat _rotation;
mutable osg::buffered_value<float> _scale;
float _autoUpdateEyeMovementTolerance;
bool _autoRotateToScreen; bool _autoRotateToScreen;
bool _autoScaleToLimitScreenSizeToFontResolution;
Layout _layout; Layout _layout;
osg::Vec4 _color; osg::Vec4 _color;
unsigned int _drawMode; unsigned int _drawMode;
// iternal map used for rendering. Set up by the computeGlyphRepresentation() method. // iternal map used for rendering. Set up by the computeGlyphRepresentation() method.
TextureGlyphQuadMap _textureGlyphQuadMap; mutable TextureGlyphQuadMap _textureGlyphQuadMap;
void computeGlyphRepresentation(); void computeGlyphRepresentation();
// internal caches of the positioning of the text. // internal caches of the positioning of the text.
mutable osg::buffered_object<osg::Matrix> _matrix;
osg::Vec3 _offset; struct AutoTransformCache
osg::Vec3 _normal; {
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; mutable osg::BoundingBox _textBB;
void setUpAutoCallback();
void computePositions(); 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: protected:
/** prevent unwanted copy construction.*/ // /** prevent unwanted copy construction.*/
CullVisitor(const CullVisitor&):osg::NodeVisitor(),osg::CullStack() {} // CullVisitor(const CullVisitor&): osg::NodeVisitor(), osg::CullStack() {}
/** prevent unwanted copy operator.*/ /** prevent unwanted copy operator.*/
CullVisitor& operator = (const CullVisitor&) { return *this; } 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; } 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; } 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; } 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.*/ /** Set the LOD bias for the CullVisitor to use.*/
void setLODScale(float bias) { _LODScale = bias; } void setLODScale(float bias) { _LODScale = bias; }

View File

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

View File

@ -11,6 +11,7 @@
* OpenSceneGraph Public License for more details. * OpenSceneGraph Public License for more details.
*/ */
#include <osg/CullStack> #include <osg/CullStack>
#include <osg/Timer>
using namespace osg; using namespace osg;
@ -200,25 +201,77 @@ void CullStack::pushModelViewMatrix(RefMatrix* matrix)
pushCullingSet(); 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. // 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_0 = (*matrix)(0,0);
const float x_1 = (*matrix)(1,0); const float x_1 = (*matrix)(1,0);
const float x_2 = (*matrix)(2,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_0 = (*matrix)(0,1);
const float y_1 = (*matrix)(1,1); const float y_1 = (*matrix)(1,1);
const float y_2 = (*matrix)(2,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_0 = (*matrix)(0,2);
const float z_1 = (*matrix)(1,2); const float z_1 = (*matrix)(1,2);
const float z_2 = (*matrix)(2,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);
_eyePointStack.push_back(osg::Vec3(x_0*x_scale + y_0*y_scale + z_0*z_scale,
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_1*x_scale + y_1*y_scale + z_1*z_scale,
x_2*x_scale + y_2*y_scale + z_2*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;
}
osg::Vec3 lookVector = getLookVectorLocal(); osg::Vec3 lookVector = getLookVectorLocal();

View File

@ -257,8 +257,18 @@ struct ComputeBound : public Drawable::PrimitiveFunctor
{ {
ComputeBound():_vertices(0) {} 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,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) virtual void drawArrays(GLenum,GLint first,GLsizei count)
{ {
if (_vertices) if (_vertices)
@ -305,8 +315,12 @@ struct ComputeBound : public Drawable::PrimitiveFunctor
} }
virtual void begin(GLenum) {} 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 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) { _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() {} virtual void end() {}
const Vec3* _vertices; const Vec3* _vertices;

View File

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

View File

@ -16,21 +16,25 @@
using namespace osg; using namespace osg;
class DrawVertex class DrawVertex : public osg::ConstValueVisitor
{ {
public: public:
DrawVertex(const Vec3Array* vertices,const IndexArray* indices): DrawVertex(const Array* vertices,const IndexArray* indices):
_vertices(vertices), _vertices(vertices),
_indices(indices) {} _indices(indices) {}
void operator () (unsigned int pos) void operator () (unsigned int pos)
{ {
if (_indices) glVertex3fv((*_vertices)[_indices->index(pos)].ptr()); if (_indices) _vertices->accept(_indices->index(pos),*this);
else glVertex3fv((*_vertices)[pos].ptr()); else _vertices->accept(pos,*this);
} }
const Vec3Array* _vertices; 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; const IndexArray* _indices;
}; };
@ -813,7 +817,7 @@ void Geometry::drawImplementation(State& state) const
// //
if( _vertexArray.valid() ) if( _vertexArray.valid() )
state.setVertexPointer(3,GL_FLOAT,0,_vertexArray->getDataPointer()); state.setVertexPointer(_vertexArray->getDataSize(),_vertexArray->getDataType(),0,_vertexArray->getDataPointer());
else else
state.disableVertexPointer(); state.disableVertexPointer();
@ -1547,12 +1551,25 @@ void Geometry::accept(ConstAttributeFunctor& af) const
void Geometry::accept(PrimitiveFunctor& functor) const void Geometry::accept(PrimitiveFunctor& functor) const
{ {
if (!_vertexArray.valid() || _vertexArray->empty()) return; if (!_vertexArray.valid() || _vertexArray->getNumElements()==0) return;
if (!_vertexIndices.valid()) 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(); for(PrimitiveSetList::const_iterator itr=_primitives.begin();
itr!=_primitives.end(); itr!=_primitives.end();
@ -1563,6 +1580,27 @@ void Geometry::accept(PrimitiveFunctor& functor) const
} }
else 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(); for(PrimitiveSetList::const_iterator itr=_primitives.begin();
itr!=_primitives.end(); itr!=_primitives.end();
++itr) ++itr)
@ -1581,7 +1619,21 @@ void Geometry::accept(PrimitiveFunctor& functor) const
vindex<indexEnd; vindex<indexEnd;
++vindex) ++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(); functor.end();
@ -1601,7 +1653,20 @@ void Geometry::accept(PrimitiveFunctor& functor) const
for(GLsizei primCount=0;primCount<*primItr;++primCount) 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; ++vindex;
} }
@ -1621,7 +1686,20 @@ void Geometry::accept(PrimitiveFunctor& functor) const
++primCount,++primItr) ++primCount,++primItr)
{ {
unsigned int vindex=*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(); functor.end();
@ -1637,7 +1715,20 @@ void Geometry::accept(PrimitiveFunctor& functor) const
++primItr) ++primItr)
{ {
unsigned int vindex=*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(); functor.end();
@ -1653,7 +1744,20 @@ void Geometry::accept(PrimitiveFunctor& functor) const
++primItr) ++primItr)
{ {
unsigned int vindex=*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(); functor.end();
@ -1742,7 +1846,7 @@ void Geometry::computeCorrectBindingsAndArraySizes()
{ {
if (verifyBindings()) return; if (verifyBindings()) return;
if (!_vertexArray.valid() || _vertexArray->empty()) if (!_vertexArray.valid() || _vertexArray->getNumElements()==0)
{ {
// no vertex array so switch everything off. // no vertex array so switch everything off.

View File

@ -142,6 +142,7 @@ unsigned int Image::computeNumComponents(GLenum format)
switch(format) switch(format)
{ {
case(GL_COMPRESSED_RGB_S3TC_DXT1_EXT): return 3; 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_DXT3_EXT): return 4;
case(GL_COMPRESSED_RGBA_S3TC_DXT5_EXT): return 4; case(GL_COMPRESSED_RGBA_S3TC_DXT5_EXT): return 4;
case(GL_COLOR_INDEX): return 1; case(GL_COLOR_INDEX): return 1;
@ -157,7 +158,11 @@ unsigned int Image::computeNumComponents(GLenum format)
case(GL_BGRA): return 4; case(GL_BGRA): return 4;
case(GL_LUMINANCE): return 1; case(GL_LUMINANCE): return 1;
case(GL_LUMINANCE_ALPHA): return 2; case(GL_LUMINANCE_ALPHA): return 2;
default: return 0; default:
{
std::cout<<"error format = "<<std::hex<<format<<std::endl;
return 0;
}
} }
} }
@ -168,6 +173,8 @@ unsigned int Image::computePixelSizeInBits(GLenum format,GLenum type)
{ {
case(GL_COMPRESSED_RGB_S3TC_DXT1_EXT): return 4; 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; case(GL_COMPRESSED_RGBA_S3TC_DXT3_EXT): return 8;
case(GL_COMPRESSED_RGBA_S3TC_DXT5_EXT): return 8; case(GL_COMPRESSED_RGBA_S3TC_DXT5_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_8_8_8_8_REV):
case(GL_UNSIGNED_INT_10_10_10_2): case(GL_UNSIGNED_INT_10_10_10_2):
case(GL_UNSIGNED_INT_2_10_10_10_REV): return 32; 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); unsigned int pixelSize = computePixelSizeInBits(format,type);
int widthInBits = width*pixelSize; int widthInBits = width*pixelSize;
int packingInBits = packing*8; 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; return (widthInBits/packingInBits + ((widthInBits%packingInBits)?1:0))*packing;
} }
@ -227,6 +239,40 @@ int Image::computeNearestPowerOfTwo(int s,float bias)
return s; 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) void Image::setInternalTextureFormat(GLint internalFormat)
{ {
// won't do any sanity checking right now, leave it to // 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): case(FRONT):
_ambientFrontAndBack = false; _ambientFrontAndBack = false;
_ambientFront = ambient; _ambientFront = ambient;
clampArray4BetweenRange(_ambientFront,0.0f,1.0f,"osg::Material::setAmbient(..)"); //clampArray4BetweenRange(_ambientFront,0.0f,1.0f,"osg::Material::setAmbient(..)");
break; break;
case(BACK): case(BACK):
_ambientFrontAndBack = false; _ambientFrontAndBack = false;
_ambientBack = ambient; _ambientBack = ambient;
clampArray4BetweenRange(_ambientBack,0.0f,1.0f,"Material::setAmbient(..)"); //clampArray4BetweenRange(_ambientBack,0.0f,1.0f,"Material::setAmbient(..)");
break; break;
case(FRONT_AND_BACK): case(FRONT_AND_BACK):
_ambientFrontAndBack = true; _ambientFrontAndBack = true;
_ambientFront = ambient; _ambientFront = ambient;
clampArray4BetweenRange(_ambientFront,0.0f,1.0f,"Material::setAmbient(..)"); //clampArray4BetweenRange(_ambientFront,0.0f,1.0f,"Material::setAmbient(..)");
_ambientBack = _ambientFront; _ambientBack = _ambientFront;
break; break;
default: default:
@ -100,17 +100,17 @@ void Material::setDiffuse(Face face, const Vec4& diffuse )
case(FRONT): case(FRONT):
_diffuseFrontAndBack = false; _diffuseFrontAndBack = false;
_diffuseFront = diffuse; _diffuseFront = diffuse;
clampArray4BetweenRange(_diffuseFront,0.0f,1.0f,"Material::setDiffuse(..)"); //clampArray4BetweenRange(_diffuseFront,0.0f,1.0f,"Material::setDiffuse(..)");
break; break;
case(BACK): case(BACK):
_diffuseFrontAndBack = false; _diffuseFrontAndBack = false;
_diffuseBack = diffuse; _diffuseBack = diffuse;
clampArray4BetweenRange(_diffuseBack,0.0f,1.0f,"Material::setDiffuse(..)"); //clampArray4BetweenRange(_diffuseBack,0.0f,1.0f,"Material::setDiffuse(..)");
break; break;
case(FRONT_AND_BACK): case(FRONT_AND_BACK):
_diffuseFrontAndBack = true; _diffuseFrontAndBack = true;
_diffuseFront = diffuse; _diffuseFront = diffuse;
clampArray4BetweenRange(_diffuseFront,0.0f,1.0f,"Material::setDiffuse(..)"); //clampArray4BetweenRange(_diffuseFront,0.0f,1.0f,"Material::setDiffuse(..)");
_diffuseBack = _diffuseFront; _diffuseBack = _diffuseFront;
break; break;
default: default:
@ -148,17 +148,17 @@ void Material::setSpecular(Face face, const Vec4& specular )
case(FRONT): case(FRONT):
_specularFrontAndBack = false; _specularFrontAndBack = false;
_specularFront = specular; _specularFront = specular;
clampArray4BetweenRange(_specularFront,0.0f,1.0f,"Material::setSpecular(..)"); //clampArray4BetweenRange(_specularFront,0.0f,1.0f,"Material::setSpecular(..)");
break; break;
case(BACK): case(BACK):
_specularFrontAndBack = false; _specularFrontAndBack = false;
_specularBack = specular; _specularBack = specular;
clampArray4BetweenRange(_specularBack,0.0f,1.0f,"Material::setSpecular(..)"); //clampArray4BetweenRange(_specularBack,0.0f,1.0f,"Material::setSpecular(..)");
break; break;
case(FRONT_AND_BACK): case(FRONT_AND_BACK):
_specularFrontAndBack = true; _specularFrontAndBack = true;
_specularFront = specular; _specularFront = specular;
clampArray4BetweenRange(_specularFront,0.0f,1.0f,"Material::setSpecular(..)"); //clampArray4BetweenRange(_specularFront,0.0f,1.0f,"Material::setSpecular(..)");
_specularBack = _specularFront; _specularBack = _specularFront;
break; break;
default: default:
@ -196,17 +196,17 @@ void Material::setEmission(Face face, const Vec4& emission )
case(FRONT): case(FRONT):
_emissionFrontAndBack = false; _emissionFrontAndBack = false;
_emissionFront = emission; _emissionFront = emission;
clampArray4BetweenRange(_emissionFront,0.0f,1.0f,"Material::setEmission(..)"); //clampArray4BetweenRange(_emissionFront,0.0f,1.0f,"Material::setEmission(..)");
break; break;
case(BACK): case(BACK):
_emissionFrontAndBack = false; _emissionFrontAndBack = false;
_emissionBack = emission; _emissionBack = emission;
clampArray4BetweenRange(_emissionBack,0.0f,1.0f,"Material::setEmission(..)"); //clampArray4BetweenRange(_emissionBack,0.0f,1.0f,"Material::setEmission(..)");
break; break;
case(FRONT_AND_BACK): case(FRONT_AND_BACK):
_emissionFrontAndBack = true; _emissionFrontAndBack = true;
_emissionFront = emission; _emissionFront = emission;
clampArray4BetweenRange(_emissionFront,0.0f,1.0f,"Material::setEmission(..)"); //clampArray4BetweenRange(_emissionFront,0.0f,1.0f,"Material::setEmission(..)");
_emissionBack = _emissionFront; _emissionBack = _emissionFront;
break; break;
default: default:
@ -285,7 +285,7 @@ float Material::getShininess(Face face) const
void Material::setTransparency(Face face,float transparency) 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) if (face==FRONT || face==FRONT_AND_BACK)
{ {

View File

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

View File

@ -55,7 +55,10 @@ Point::Point()
_size = 1.0f; // TODO find proper default _size = 1.0f; // TODO find proper default
_fadeThresholdSize = 1.0f; // TODO find proper default _fadeThresholdSize = 1.0f; // TODO find proper default
// 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; _distanceAttenuation = distanceAttenuation;
} }
void Point::setMinSize(float minSize)
{
_minSize = minSize;
}
void Point::setMaxSize(float maxSize)
{
_maxSize = maxSize;
}
void Point::apply(State&) const void Point::apply(State&) const
{ {
@ -112,8 +124,14 @@ void Point::apply(State&) const
init_GL_EXT(); 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> #include <osg/GLExtensions>
using namespace std;
using namespace osg; using namespace osg;
State::State() State::State()
@ -726,7 +727,7 @@ bool State::checkGLErrors(StateAttribute::GLMode mode) const
GLenum errorNo = glGetError(); GLenum errorNo = glGetError();
if (errorNo!=GL_NO_ERROR) 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 true;
} }
return false; return false;

View File

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

View File

@ -23,6 +23,11 @@ TextureRectangle::TextureRectangle():
_textureWidth(0), _textureWidth(0),
_textureHeight(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): TextureRectangle::TextureRectangle(const TextureRectangle& text,const CopyOp& copyop):
@ -132,7 +137,7 @@ void TextureRectangle::apply(State& state) const
applyTexParameters(GL_TEXTURE_RECTANGLE_NV, state); 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 // in theory the following line is redundant, but in practice
// have found that the first frame drawn doesn't apply the textures // 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 we don't have a valid image we can't create a texture!
if (!image || !image->data()) if (!image || !image->data())

View File

@ -51,7 +51,8 @@ Registry* Registry::instance()
// definition of the Registry // definition of the Registry
Registry::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; _createNodeFromImage = true;
_openingLibrary = false; _openingLibrary = false;
@ -126,16 +127,16 @@ void Registry::initDataFilePathList()
char *ptr; char *ptr;
if( (ptr = getenv( "OSG_FILE_PATH" )) ) 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); setDataFilePathList(ptr);
} }
else if( (ptr = getenv( "OSGFILEPATH" )) ) else if( (ptr = getenv( "OSGFILEPATH" )) )
{ {
notify(DEBUG_INFO) << "OSGFILEPATH("<<ptr<<")"<<std::endl; //notify(DEBUG_INFO) << "OSGFILEPATH("<<ptr<<")"<<std::endl;
setDataFilePathList(ptr); setDataFilePathList(ptr);
} }
osg::notify(INFO)<<"Data FilePathList"<<std::endl; //osg::notify(INFO)<<"Data FilePathList"<<std::endl;
PrintFilePathList(osg::notify(INFO),getDataFilePathList()); PrintFilePathList(osg::notify(INFO),getDataFilePathList());
} }
@ -153,12 +154,12 @@ void Registry::initLibraryFilePathList()
char* ptr; char* ptr;
if( (ptr = getenv( "OSG_LIBRARY_PATH")) ) 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); setLibraryFilePathList(ptr);
} }
else if( (ptr = getenv( "OSG_LD_LIBRARY_PATH")) ) 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); setLibraryFilePathList(ptr);
} }
@ -227,8 +228,8 @@ void Registry::initLibraryFilePathList()
#endif #endif
osg::notify(INFO)<<"Library FilePathList"<<std::endl; //osg::notify(INFO)<<"Library FilePathList"<<std::endl;
PrintFilePathList(osg::notify(INFO),getLibraryFilePathList()); //PrintFilePathList(osg::notify(INFO),getLibraryFilePathList());
} }

View File

@ -3,7 +3,7 @@
void osgGA::GUIEventHandlerVisitor::visit(osgGA::CompositeGUIEventHandler& cgeh) 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); cgeh.getChild(i)->accept(*this);
} }
} }

View File

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

View File

@ -156,7 +156,10 @@ osg::Image* ReadDDSFile(const char *filename)
fread(&ddsd, sizeof(ddsd), 1, fp); fread(&ddsd, sizeof(ddsd), 1, fp);
// Read image data. // Read image data.
unsigned int size = ddsd.dwMipMapCount > 1 ? ddsd.dwLinearSize * 2 : ddsd.dwLinearSize; 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]; unsigned char* imageData = new unsigned char [size];
fread(imageData, 1, size, fp); fread(imageData, 1, size, fp);
// Close the file. // Close the file.
@ -206,7 +209,8 @@ osg::Image* ReadDDSFile(const char *filename)
else else
{ {
internalFormat = GL_COMPRESSED_RGB_S3TC_DXT1_EXT; 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; break;
case FOURCC_DXT3: case FOURCC_DXT3:

View File

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

View File

@ -1838,11 +1838,25 @@ void ConvertFromFLT::visitLightPoint(GeoSetBuilder* pBuilder, LightPointRecord*
osg::Point* point = new osg::Point; osg::Point* point = new osg::Point;
if (point) if (point)
{ {
/*
point->setSize(pSLightPoint->sfSize); point->setSize(pSLightPoint->sfSize);
stateSet->setAttributeAndModes( point, osg::StateAttribute::ON ); stateSet->setAttributeAndModes( point, osg::StateAttribute::ON );
// point->setFadeThresholdSize(const float fadeThresholdSize); // point->setFadeThresholdSize(const float fadeThresholdSize);
// point->setDistanceAttenuation(const Vec3& distanceAttenuation); // point->setDistanceAttenuation(const Vec3& distanceAttenuation);
// point->setStateSetModes(*stateSet, osg::StateAttribute::ON); // GL_POINT_SMOOTH // 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 "FreeTypeFont.h"
#include FT_GLYPH_H //#include FT_GLYPH_H
#include <osg/Notify> #include <osg/Notify>
#include <osgDB/WriteFile> #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 FT_Error error = FT_Get_Kerning( _face, // handle to face object
left, // left glyph index left, // left glyph index
right, // right glyph index right, // right glyph index
ft_kerning_default, // kerning mode FT_KERNING_UNFITTED, // kerning mode
&kerning ); // target vector &kerning ); // target vector
if (error) if (error)

View File

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

View File

@ -14,6 +14,34 @@
#include "DataInputStream.h" #include "DataInputStream.h"
#include "StateSet.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> #include <osgDB/ReadFile>
using namespace ive; using namespace ive;
@ -62,6 +90,14 @@ unsigned short DataInputStream::readUShort(){
return s; 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(){ int DataInputStream::readInt(){
if(_peeking){ if(_peeking){
_peeking = false; _peeking = false;
@ -130,25 +166,34 @@ void DataInputStream::readCharArray(char* data, int size){
osg::Vec2 DataInputStream::readVec2(){ osg::Vec2 DataInputStream::readVec2(){
osg::Vec2 v; osg::Vec2 v;
v.set(readFloat(), readFloat()); v.x()=readFloat();
v.y()=readFloat();
return v; return v;
} }
osg::Vec3 DataInputStream::readVec3(){ osg::Vec3 DataInputStream::readVec3(){
osg::Vec3 v; osg::Vec3 v;
v.set(readFloat(),readFloat(),readFloat()); v.x()=readFloat();
v.y()=readFloat();
v.z()=readFloat();
return v; return v;
} }
osg::Vec4 DataInputStream::readVec4(){ osg::Vec4 DataInputStream::readVec4(){
osg::Vec4 v; osg::Vec4 v;
v.set(readFloat(), readFloat(), readFloat(), readFloat()); v.x()=readFloat();
v.y()=readFloat();
v.z()=readFloat();
v.w()=readFloat();
return v; return v;
} }
osg::UByte4 DataInputStream::readUByte4(){ osg::UByte4 DataInputStream::readUByte4(){
osg::UByte4 v; osg::UByte4 v;
v.set(readChar(), readChar(), readChar(), readChar()); v.r()=readChar();
v.g()=readChar();
v.b()=readChar();
v.a()=readChar();
return v; return v;
} }
@ -158,46 +203,6 @@ osg::Quat DataInputStream::readQuat(){
return q; 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;
}
@ -231,96 +236,356 @@ osg::Array* DataInputStream::readArray(){
osg::IntArray* DataInputStream::readIntArray(){ osg::IntArray* DataInputStream::readIntArray(){
int size = readInt(); int size = readInt();
osg::IntArray* a = new osg::IntArray(); osg::IntArray* a = new osg::IntArray(size);
a->reserve(size);
for(int i =0; i<size;i++){ _istream->read((char*)&((*a)[0]), INTSIZE*size);
a->push_back(readInt()); 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; return a;
} }
osg::UByteArray* DataInputStream::readUByteArray(){ osg::UByteArray* DataInputStream::readUByteArray(){
int size = readInt(); int size = readInt();
osg::UByteArray* a = new osg::UByteArray(); osg::UByteArray* a = new osg::UByteArray(size);
a->reserve(size);
for(int i =0; i<size;i++){ _istream->read((char*)&((*a)[0]), CHARSIZE*size);
a->push_back(readChar()); 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; return a;
} }
osg::UShortArray* DataInputStream::readUShortArray(){ osg::UShortArray* DataInputStream::readUShortArray(){
int size = readInt(); int size = readInt();
osg::UShortArray* a = new osg::UShortArray(); osg::UShortArray* a = new osg::UShortArray(size);
a->reserve(size);
for(int i =0; i<size;i++){ _istream->read((char*)&((*a)[0]), SHORTSIZE*size);
a->push_back(readUShort()); 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; return a;
} }
osg::UIntArray* DataInputStream::readUIntArray(){ osg::UIntArray* DataInputStream::readUIntArray(){
int size = readInt(); int size = readInt();
osg::UIntArray* a = new osg::UIntArray(); osg::UIntArray* a = new osg::UIntArray(size);
a->reserve(size);
for(int i =0; i<size;i++){ _istream->read((char*)&((*a)[0]), INTSIZE*size);
a->push_back((unsigned int)readInt()); 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; return a;
} }
osg::UByte4Array* DataInputStream::readUByte4Array(){ osg::UByte4Array* DataInputStream::readUByte4Array(){
int size = readInt(); int size = readInt();
osg::UByte4Array* a = new osg::UByte4Array(); osg::UByte4Array* a = new osg::UByte4Array(size);
a->reserve(size);
for(int i =0; i<size;i++){ _istream->read((char*)&((*a)[0]), INTSIZE*size);
a->push_back(readUByte4()); 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; return a;
} }
osg::FloatArray* DataInputStream::readFloatArray(){ osg::FloatArray* DataInputStream::readFloatArray(){
int size = readInt(); int size = readInt();
osg::FloatArray* a = new osg::FloatArray(); osg::FloatArray* a = new osg::FloatArray(size);
a->reserve(size);
for(int i =0; i<size;i++){ _istream->read((char*)&((*a)[0]), FLOATSIZE*size);
a->push_back(readFloat()); 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; return a;
} }
osg::Vec2Array* DataInputStream::readVec2Array(){ osg::Vec2Array* DataInputStream::readVec2Array(){
int size = readInt(); int size = readInt();
osg::Vec2Array* a = new osg::Vec2Array(size); osg::Vec2Array* a = new osg::Vec2Array(size);
for(int i = 0; i < size; i++){
(*a)[i] = (readVec2()); _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; return a;
} }
osg::Vec3Array* DataInputStream::readVec3Array(){ osg::Vec3Array* DataInputStream::readVec3Array(){
int size = readInt(); int size = readInt();
osg::Vec3Array* a = new osg::Vec3Array(size); osg::Vec3Array* a = new osg::Vec3Array(size);
for(int i = 0; i < size; i++){
(*a)[i] = readVec3(); _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; return a;
} }
osg::Vec4Array* DataInputStream::readVec4Array(){ osg::Vec4Array* DataInputStream::readVec4Array(){
int size = readInt(); int size = readInt();
osg::Vec4Array* a = new osg::Vec4Array(size); osg::Vec4Array* a = new osg::Vec4Array(size);
for(int i = 0; i < size; i++){
(*a)[i] = (readVec4()); _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; return a;
} }
osg::Matrix DataInputStream::readMatrix(){ osg::Matrix DataInputStream::readMatrix(){
osg::Matrix mat; osg::Matrix mat;
float* p = mat.ptr(); _istream->read((char*)(mat.ptr()), FLOATSIZE*16);
for(int i=0;i<16;i++){ if (_istream->rdstate() & _istream->failbit)
p[i] = readFloat(); 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; 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(); bool readBool();
char readChar(); char readChar();
unsigned short readUShort(); unsigned short readUShort();
unsigned int readUInt();
int readInt(); int readInt();
int peekInt(); int peekInt();
float readFloat(); float readFloat();
@ -46,8 +47,6 @@ public:
osg::Quat readQuat(); osg::Quat readQuat();
osg::Matrix readMatrix(); osg::Matrix readMatrix();
osg::Geometry::AttributeBinding readBinding(); osg::Geometry::AttributeBinding readBinding();
osg::Image* readImage(std::string s);
osg::StateSet* readStateSet();
osg::Array* readArray(); osg::Array* readArray();
osg::IntArray* readIntArray(); osg::IntArray* readIntArray();
osg::UByteArray* readUByteArray(); osg::UByteArray* readUByteArray();
@ -59,13 +58,17 @@ public:
osg::Vec3Array* readVec3Array(); osg::Vec3Array* readVec3Array();
osg::Vec4Array* readVec4Array(); osg::Vec4Array* readVec4Array();
// Container to map image filenames to their respective images. osg::Image* readImage(std::string s);
typedef std::pair<std::string, osg::ref_ptr<osg::Image> > ImagePair; osg::StateSet* readStateSet();
typedef std::vector<ImagePair> ImageList; osg::StateAttribute* readStateAttribute();
osg::Drawable* readDrawable();
osg::Node* readNode();
// Container to map stateset id to their respective stateset. typedef std::map<std::string, osg::ref_ptr<osg::Image> > ImageMap;
typedef std::pair<int, osg::ref_ptr<osg::StateSet> > StateSetPair; typedef std::map<int,osg::ref_ptr<osg::StateSet> > StateSetMap;
typedef std::vector<StateSetPair> StateSetList; 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: private:
@ -73,8 +76,11 @@ private:
int _version; int _version;
bool _peeking; bool _peeking;
int _peekValue; int _peekValue;
ImageList _imageList; ImageMap _imageMap;
StateSetList _statesetList; StateSetMap _statesetMap;
StateAttributeMap _stateAttributeMap;
DrawableMap _drawableMap;
NodeMap _nodeMap;
}; };
} }

View File

@ -14,7 +14,35 @@
#include "DataOutputStream.h" #include "DataOutputStream.h"
#include "Exception.h" #include "Exception.h"
#include "StateSet.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; using namespace ive;
@ -41,6 +69,10 @@ 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){ void DataOutputStream::writeInt(int i){
_ostream->write((char*)&i, INTSIZE); _ostream->write((char*)&i, INTSIZE);
} }
@ -66,55 +98,36 @@ void DataOutputStream::writeCharArray(char* data, int size){
_ostream->write(data, size); _ostream->write(data, size);
} }
void DataOutputStream::writeVec2(osg::Vec2 v){ void DataOutputStream::writeVec2(const osg::Vec2& v){
writeFloat(v.y());
writeFloat(v.x()); writeFloat(v.x());
writeFloat(v.y());
} }
void DataOutputStream::writeVec3(osg::Vec3 v){ void DataOutputStream::writeVec3(const osg::Vec3& v){
writeFloat(v.x());
writeFloat(v.y());
writeFloat(v.z()); writeFloat(v.z());
writeFloat(v.y());
writeFloat(v.x());
} }
void DataOutputStream::writeVec4(osg::Vec4 v){ void DataOutputStream::writeVec4(const osg::Vec4& v){
writeFloat(v.x());
writeFloat(v.y());
writeFloat(v.z());
writeFloat(v.w()); writeFloat(v.w());
writeFloat(v.z());
writeFloat(v.y());
writeFloat(v.x());
} }
void DataOutputStream::writeUByte4(osg::UByte4 v){ void DataOutputStream::writeUByte4(const osg::UByte4& v){
writeChar(v.a());
writeChar(v.b());
writeChar(v.g());
writeChar(v.r()); writeChar(v.r());
writeChar(v.g());
writeChar(v.b());
writeChar(v.a());
} }
void DataOutputStream::writeQuat(osg::Quat q){ void DataOutputStream::writeQuat(const osg::Quat& q){
writeFloat(q.w());
writeFloat(q.z());
writeFloat(q.y());
writeFloat(q.x()); writeFloat(q.x());
} writeFloat(q.y());
writeFloat(q.z());
void DataOutputStream::writeStateSet(osg::StateSet* stateset){ writeFloat(q.w());
// 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::writeBinding(osg::Geometry::AttributeBinding b){ void DataOutputStream::writeBinding(osg::Geometry::AttributeBinding b){
@ -250,3 +263,187 @@ void DataOutputStream::writeMatrix(osg::Matrix mat){
writeFloat(p[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 writeBool(bool b);
void writeChar(char c); void writeChar(char c);
void writeUShort(unsigned short s); void writeUShort(unsigned short s);
void writeUInt(unsigned int s);
void writeInt(int i); void writeInt(int i);
void writeFloat(float f); void writeFloat(float f);
void writeLong(long l); void writeLong(long l);
void writeDouble(double d); void writeDouble(double d);
void writeString(std::string s); void writeString(std::string s);
void writeCharArray(char* data, int size); void writeCharArray(char* data, int size);
void writeVec2(osg::Vec2 v); void writeVec2(const osg::Vec2& v);
void writeVec3(osg::Vec3 v); void writeVec3(const osg::Vec3& v);
void writeVec4(osg::Vec4 v); void writeVec4(const osg::Vec4& v);
void writeUByte4(osg::UByte4 v); void writeUByte4(const osg::UByte4& v);
void writeQuat(osg::Quat q); void writeQuat(const osg::Quat& q);
void writeStateSet(osg::StateSet* stateset);
void writeBinding(osg::Geometry::AttributeBinding b); void writeBinding(osg::Geometry::AttributeBinding b);
void writeArray(osg::Array* a); void writeArray(osg::Array* a);
void writeIntArray(osg::IntArray* a); void writeIntArray(osg::IntArray* a);
@ -54,6 +54,11 @@ public:
void writeVec4Array(osg::Vec4Array* a); void writeVec4Array(osg::Vec4Array* a);
void writeMatrix(osg::Matrix mat); 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 // Set and get include image data in stream
void setIncludeImageData(bool b) {_includeImageData=b;}; void setIncludeImageData(bool b) {_includeImageData=b;};
bool getIncludeImageData() {return _includeImageData;}; bool getIncludeImageData() {return _includeImageData;};
@ -62,8 +67,15 @@ private:
std::ostream* _ostream; std::ostream* _ostream;
// Container to map stateset uniques to their respective stateset. // Container to map stateset uniques to their respective stateset.
typedef std::vector<int> StateSetList; typedef std::map<osg::StateSet*,int> StateSetMap;
StateSetList _statesetList; 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 Drawable's properties.
// Write stateset. // Write stateset if any
out->writeInt((int)getStateSet());
if (getStateSet()) if (getStateSet())
{
out->writeInt(1); //true we have a stateset
out->writeStateSet(getStateSet()); out->writeStateSet(getStateSet());
}
else
out->writeInt(0); //false we don't have a stateset
// Write shape // Write shape
out->writeInt((int)getShape()); if (getShape())
if (getShape()){ {
out->writeInt(1); //true we have a shape
//static_cast<Shape*>(getShape())->write(out); //static_cast<Shape*>(getShape())->write(out);
} }
else
out->writeInt(0); //false we don't have a shape
// Write support display list. // Write support display list.
out->writeBool(getSupportsDisplayList()); out->writeBool(getSupportsDisplayList());

View File

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

View File

@ -41,11 +41,15 @@ void Geode::write(DataOutputStream* out){
// Write out every drawable. // Write out every drawable.
for(unsigned int i=0;i<getNumDrawables();i++){ for(unsigned int i=0;i<getNumDrawables();i++){
osg::Drawable* drawable = getDrawable(i); osg::Drawable* drawable = getDrawable(i);
#if 0
if(dynamic_cast<osg::Geometry*>(drawable)) if(dynamic_cast<osg::Geometry*>(drawable))
((ive::Geometry*)(drawable))->write(out); ((ive::Geometry*)(drawable))->write(out);
else{ else{
throw Exception("Unknown drawable in Geode::write()"); throw Exception("Unknown drawable in Geode::write()");
} }
#else
out->writeDrawable(drawable);
#endif
} }
} }
@ -68,6 +72,7 @@ void Geode::read(DataInputStream* in){
int size = in->readInt(); int size = in->readInt();
// Read the drawables. // Read the drawables.
for(int i = 0; i<size; i++){ for(int i = 0; i<size; i++){
#if 0
int id = in->peekInt(); int id = in->peekInt();
osg::Drawable* drawable; osg::Drawable* drawable;
if(id == IVEGEOMETRY){ if(id == IVEGEOMETRY){
@ -77,7 +82,9 @@ void Geode::read(DataInputStream* in){
} }
else else
throw Exception("Unknown drawable identification in Geode::read()"); throw Exception("Unknown drawable identification in Geode::read()");
#else
addDrawable(in->readDrawable());
#endif
} }
} }
else{ else{

View File

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

View File

@ -45,38 +45,7 @@ void Group::write(DataOutputStream* out){
// Write children. // Write children.
for(unsigned int i=0; i<getNumChildren(); i++){ for(unsigned int i=0; i<getNumChildren(); i++){
osg::Node* child = getChild(i); osg::Node* child = getChild(i);
if(dynamic_cast<osg::MatrixTransform*>(child)){ out->writeNode(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()");
} }
} }
@ -101,62 +70,9 @@ void Group::read(DataInputStream* in){
// Read number of children. // Read number of children.
int size = in->readInt(); int size = in->readInt();
// Read children. // Read children.
for(int i=0; i<size; i++){ for(int i=0; i<size; i++)
int id = in->peekInt(); {
osg::Node* child; addChild(in->readNode());
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{ else{

View File

@ -18,7 +18,8 @@
using namespace ive; using namespace ive;
void Image::write(DataOutputStream* out){ void Image::write(DataOutputStream* out)
{
// Write Image's identification. // Write Image's identification.
out->writeInt(IVEIMAGE); out->writeInt(IVEIMAGE);
// If the osg class is inherited by any other class we should also write this to file. // If the osg class is inherited by any other class we should also write this to file.
@ -38,6 +39,9 @@ void Image::write(DataOutputStream* out){
out->writeInt(t()); out->writeInt(t());
out->writeInt(r()); 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(getInternalTextureFormat());
out->writeInt(getPixelFormat()); out->writeInt(getPixelFormat());
@ -54,10 +58,10 @@ void Image::write(DataOutputStream* out){
out->writeInt(_mipmapData[i]); out->writeInt(_mipmapData[i]);
// Write image data if any // Write image data if any
out->writeInt((int)data()); out->writeLong((long)data());
if(data()){ if(data()){
// Compute the size of image data and write this. // Compute the size of image data and write this.
unsigned int size = computeRowWidthInBytes(s(),getPixelFormat(),getDataType(),getPacking())*t()*r(); unsigned int size = getTotalSizeInBytesIncludingMipmaps();
out->writeInt(size); out->writeInt(size);
// Write the data // Write the data
out->writeCharArray((char*)data(), size); out->writeCharArray((char*)data(), size);
@ -65,7 +69,8 @@ void Image::write(DataOutputStream* out){
} }
void Image::read(DataInputStream* in){ void Image::read(DataInputStream* in)
{
// Peek Image's identification. // Peek Image's identification.
int id = in->peekInt(); int id = in->peekInt();
if(id == IVEIMAGE){ if(id == IVEIMAGE){
@ -84,9 +89,9 @@ void Image::read(DataInputStream* in){
setFileName(in->readString()); setFileName(in->readString());
// Read width, height, depth of image. // Read width, height, depth of image.
int s=in->readInt(); int is=in->readInt();
int t=in->readInt(); int it=in->readInt();
int r=in->readInt(); int ir=in->readInt();
// Read formats, type and packing // Read formats, type and packing
GLint internalTextureFormat = (GLint) in->readInt(); GLint internalTextureFormat = (GLint) in->readInt();
@ -100,18 +105,34 @@ void Image::read(DataInputStream* in){
// Read mipmapdata vector // Read mipmapdata vector
int size = in->readInt(); int size = in->readInt();
_mipmapData.resize(size); _mipmapData.resize(size);
//if (size) std::cout<<"is mip mapped ";
for(int i=0;i<size;i++) for(int i=0;i<size;i++)
{
_mipmapData[i]=(unsigned int)in->readInt(); _mipmapData[i]=(unsigned int)in->readInt();
//std::cout<<_mipmapData[i]<<"\t";
}
//std::cout<<std::endl;
// Read image data if any // Read image data if any
if(in->readInt()){ if(in->readInt()){
unsigned int dataSize = (unsigned int)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 = (char*)malloc (dataSize);
char* data = new char[dataSize]; char* data = new char[dataSize];
if(!data) if(!data)
throw Exception("Image::read(): Unable to allocate memory for image data."); throw Exception("Image::read(): Unable to allocate memory for image data.");
in->readCharArray(data,dataSize); in->readCharArray(data,dataSize);
setImage(s, t, r, internalTextureFormat, pixelFormat, setImage(is, it, ir, internalTextureFormat, pixelFormat,
dataType, (unsigned char* ) data, osg::Image::USE_NEW_DELETE, packing); dataType, (unsigned char* ) data, osg::Image::USE_NEW_DELETE, packing);
} }
} }

View File

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

View File

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

View File

@ -22,6 +22,11 @@ namespace ive {
#define IVETRANSFORM 0x00000013 #define IVETRANSFORM 0x00000013
#define IVEPOSITIONATTITUDETRANSFORM 0x00000014 #define IVEPOSITIONATTITUDETRANSFORM 0x00000014
#define IVEANIMATIONPATH 0x00000015 #define IVEANIMATIONPATH 0x00000015
#define IVESWITCH 0x00000016
#define IVEOCCLUDERNODE 0x00000017
#define IVEIMPOSTOR 0x00000018
#define IVECONVEXPLANAROCCLUDER 0x00000019
#define IVECONVEXPLANARPOLYGON 0x00000020
// Node callbacks // Node callbacks
#define IVENODECALLBACK 0x00000050 #define IVENODECALLBACK 0x00000050
@ -41,6 +46,9 @@ namespace ive {
#define IVETEXENVCOMBINE 0x00000126 #define IVETEXENVCOMBINE 0x00000126
#define IVETEXGEN 0x00000127 #define IVETEXGEN 0x00000127
#define IVECULLFACE 0x00000128 #define IVECULLFACE 0x00000128
#define IVEPOLYGONOFFSET 0x00000129
#define IVESHADEMODEL 0x0000012A
#define IVEPOINT 0x0000012B
// Drawables // Drawables
#define IVEDRAWABLE 0x00001000 #define IVEDRAWABLE 0x00001000
@ -51,6 +59,7 @@ namespace ive {
#define IVEDRAWARRAYS 0x00010001 #define IVEDRAWARRAYS 0x00010001
#define IVEDRAWARRAYLENGTHS 0x00010002 #define IVEDRAWARRAYLENGTHS 0x00010002
#define IVEDRAWELEMENTSUSHORT 0x00010003 #define IVEDRAWELEMENTSUSHORT 0x00010003
#define IVEDRAWELEMENTSUINT 0x00010004
// Our own classes // Our own classes
#define IVEVIEWPOINT 0x00100001 #define IVEVIEWPOINT 0x00100001

View File

@ -32,26 +32,9 @@ class IVEReaderWriter : public ReaderWriter
{ {
try{ try{
// Create datainputstream. // Create datainputstream.
ive::DataInputStream* in = new ive::DataInputStream(&fin); ive::DataInputStream in(&fin);
// Which object is written first in the stream. return in.readNode();
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;
}
} }
catch(ive::Exception e) 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) 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); std::ofstream fout(fileName.c_str(), std::ios::out | std::ios::binary);
WriteResult result = writeNode(node, fout, options); WriteResult result = writeNode(node, fout, options);
fout.close(); fout.close();
@ -73,15 +59,9 @@ class IVEReaderWriter : public ReaderWriter
{ {
try try
{ {
ive::DataOutputStream* out = new ive::DataOutputStream(&fout); ive::DataOutputStream out(&fout);
// write ive file.
if(dynamic_cast<const osg::MatrixTransform*>(&node)) out.writeNode(const_cast<osg::Node*>(&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();
return WriteResult::FILE_SAVED; return WriteResult::FILE_SAVED;
} }
catch(ive::Exception e) catch(ive::Exception e)

View File

@ -18,6 +18,8 @@
#include "BlendFunc.h" #include "BlendFunc.h"
#include "Material.h" #include "Material.h"
#include "CullFace.h" #include "CullFace.h"
#include "PolygonOffset.h"
#include "ShadeModel.h"
#include "Texture2D.h" #include "Texture2D.h"
#include "TextureCubeMap.h" #include "TextureCubeMap.h"
#include "TexEnv.h" #include "TexEnv.h"
@ -64,26 +66,9 @@ void StateSet::write(DataOutputStream* out){
// Write stateset attributes, this could for instance be alphafunctions, materials, etc. // Write stateset attributes, this could for instance be alphafunctions, materials, etc.
out->writeInt(al.size()); out->writeInt(al.size());
for(StateSet::AttributeList::iterator aitr=al.begin(); aitr!=al.end(); ++aitr){ for(StateSet::AttributeList::iterator aitr=al.begin(); aitr!=al.end(); ++aitr){
// This is a BlendFunc. out->writeStateAttribute(aitr->second.first.get());
if(dynamic_cast<osg::BlendFunc*>(aitr->second.first.get())){
((ive::BlendFunc*)(aitr->second.first.get()))->write(out);
out->writeInt(aitr->second.second); 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));
}
}
StateSet::TextureModeList tml = getTextureModeList(); StateSet::TextureModeList tml = getTextureModeList();
StateSet::TextureAttributeList tal = getTextureAttributeList(); StateSet::TextureAttributeList tal = getTextureAttributeList();
@ -108,36 +93,9 @@ void StateSet::write(DataOutputStream* out){
al = tal[unit]; al = tal[unit];
out->writeInt(al.size()); out->writeInt(al.size());
for(StateSet::AttributeList::iterator aitr=al.begin(); aitr!=al.end(); ++aitr){ for(StateSet::AttributeList::iterator aitr=al.begin(); aitr!=al.end(); ++aitr){
// This is a Texture2D out->writeStateAttribute(aitr->second.first.get());
if(dynamic_cast<osg::Texture2D*>(aitr->second.first.get())){
((ive::Texture2D*)(aitr->second.first.get()))->write(out);
out->writeInt(aitr->second.second); 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));
}
}
} }
} }
@ -188,27 +146,9 @@ void StateSet::read(DataInputStream* in){
// Read state attributes // Read state attributes
size = in->readInt(); size = in->readInt();
for(i=0;i<size;i++){ for(i=0;i<size;i++){
osg::StateAttribute* attribute; osg::StateAttribute* attribute = in->readStateAttribute();
int attributeID = in->peekInt();
if(attributeID == IVEBLENDFUNC){
attribute = new osg::BlendFunc();
((ive::BlendFunc*)(attribute))->read(in);
setAttribute(attribute, (osg::StateAttribute::OverrideValue)in->readInt()); 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. // Read texture stateset mode.
int nUnits = in->readInt(); int nUnits = in->readInt();
@ -227,37 +167,9 @@ void StateSet::read(DataInputStream* in){
for(unit=0;unit<nUnits;unit++){ for(unit=0;unit<nUnits;unit++){
size = in->readInt(); size = in->readInt();
for(i=0;i<size;i++){ for(i=0;i<size;i++){
osg::StateAttribute* attribute; osg::StateAttribute* attribute = in->readStateAttribute();
int attributeID = in->peekInt();
if(attributeID == IVETEXTURE2D){
attribute = new osg::Texture2D();
((ive::Texture2D*)(attribute))->read(in);
setTextureAttribute(unit, attribute, (osg::StateAttribute::OverrideValue)in->readInt()); 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{ else{

View File

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

View File

@ -41,27 +41,27 @@ void TextureCubeMap::write(DataOutputStream* out){
out->writeInt(getNumMipmapLevels()); out->writeInt(getNumMipmapLevels());
// Write images if any // 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)) if(getImage(osg::TextureCubeMap::POSITIVE_X))
((ive::Image*)(getImage(osg::TextureCubeMap::POSITIVE_X)))->write(out); ((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)) if(getImage(osg::TextureCubeMap::NEGATIVE_X))
((ive::Image*)(getImage(osg::TextureCubeMap::NEGATIVE_X)))->write(out); ((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)) if(getImage(osg::TextureCubeMap::POSITIVE_Y))
((ive::Image*)(getImage(osg::TextureCubeMap::POSITIVE_Y)))->write(out); ((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)) if(getImage(osg::TextureCubeMap::NEGATIVE_Y))
((ive::Image*)(getImage(osg::TextureCubeMap::NEGATIVE_Y)))->write(out); ((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)) if(getImage(osg::TextureCubeMap::POSITIVE_Z))
((ive::Image*)(getImage(osg::TextureCubeMap::POSITIVE_Z)))->write(out); ((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)) if(getImage(osg::TextureCubeMap::NEGATIVE_Z))
((ive::Image*)(getImage(osg::TextureCubeMap::NEGATIVE_Z)))->write(out); ((ive::Image*)(getImage(osg::TextureCubeMap::NEGATIVE_Z)))->write(out);

View File

@ -118,9 +118,15 @@ osgDB::ReaderWriter::ReadResult ReaderWriterOBJ::readNode(const std::string& fil
omtl->emmissive[2], omtl->emmissive[3])); omtl->emmissive[2], omtl->emmissive[3]));
// note, osg shininess scales between 0.0 and 1.0. // note, osg shininess scales between 0.0 and 1.0.
mtl->setShininess(osg::Material::FRONT_AND_BACK, omtl->shininess); mtl->setShininess(osg::Material::FRONT_AND_BACK, omtl->shininess);
mtl->setAlpha(osg::Material::FRONT_AND_BACK, omtl->alpha);
stateset->setAttribute(mtl); stateset->setAttribute(mtl);
if (omtl->alpha<1.0f) {
stateset->setMode(GL_BLEND,osg::StateAttribute::ON);
stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
}
if (omtl->textureName) if (omtl->textureName)
{ {
std::string fileName = osgDB::findFileInDirectory(omtl->textureName,directory,true); std::string fileName = osgDB::findFileInDirectory(omtl->textureName,directory,true);

View File

@ -338,6 +338,7 @@ _glmReadMTL(GLMmodel* model, char* name)
model->materials[i].specular[2] = 0.0f; model->materials[i].specular[2] = 0.0f;
model->materials[i].textureName = NULL; model->materials[i].textureName = NULL;
model->materials[i].textureReflection = false; model->materials[i].textureReflection = false;
model->materials[i].alpha = 1.0f;
} }
model->materials[0].name = strdup("default"); model->materials[0].name = strdup("default");
@ -361,6 +362,9 @@ _glmReadMTL(GLMmodel* model, char* name)
model->materials[nummaterials].shininess /= 1000.0; model->materials[nummaterials].shininess /= 1000.0;
model->materials[nummaterials].shininess *= 128.0; model->materials[nummaterials].shininess *= 128.0;
break; break;
case 'd':
fscanf(file, "%f", &model->materials[nummaterials].alpha);
break;
case 'K': case 'K':
switch(buf[1]) { switch(buf[1]) {
case 'd': case 'd':

View File

@ -46,6 +46,7 @@ struct GLMmaterial
GLfloat shininess; /* specular exponent */ GLfloat shininess; /* specular exponent */
char* textureName; /* name of any attached texture, add by RO */ char* textureName; /* name of any attached texture, add by RO */
bool textureReflection; /* true if texture is a reflection map */ bool textureReflection; /* true if texture is a reflection map */
float alpha; /* alpha */
void init() void init()
{ {
@ -57,6 +58,7 @@ struct GLMmaterial
shininess = 0.0f; shininess = 0.0f;
textureName = NULL; textureName = NULL;
textureReflection = false; textureReflection = false;
alpha = 1.0f;
} }
}; };

View File

@ -103,7 +103,7 @@ bool Geometry_readLocalData(Object& obj, Input& fr)
{ {
// post 0.9.3 releases. // post 0.9.3 releases.
++fr; ++fr;
Vec3Array* vertices = dynamic_cast<Vec3Array*>(Array_readLocalData(fr)); Array* vertices = Array_readLocalData(fr);
if (vertices) if (vertices)
{ {
geom.setVertexArray(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. // maximum dimentsions of text box.
if (fr[0].matchWord("maximumWidth")) 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")) if (fr.matchSequence("autoRotateToScreen TRUE"))
{ {
text.setAutoRotateToScreen(true); text.setAutoRotateToScreen(true);
@ -154,7 +144,7 @@ bool Text_readLocalData(osg::Object &obj, osgDB::Input &fr)
if (fr.matchSequence("autoScaleToLimitScreenSizeToFontResolution TRUE")) if (fr.matchSequence("autoScaleToLimitScreenSizeToFontResolution TRUE"))
{ {
text.setAutoScaleToLimitScreenSizeToFontResolution(true); text.setCharacterSizeMode(osgText::Text::SCREEN_COORDS);
fr += 2; fr += 2;
itAdvanced = true; itAdvanced = true;
} }
@ -263,6 +253,14 @@ bool Text_writeLocalData(const osg::Object &obj, osgDB::Output &fw)
// charater size. // charater size.
fw.indent() << "characterSize " << text.getCharacterHeight() << " " << text.getCharacterAspectRatio() << std::endl; 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. // maximum dimension of text box.
if (text.getMaximumWidth()>0.0f) 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; 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()) if (text.getAutoRotateToScreen())
{ {
fw.indent() << "autoRotateToScreen TRUE"<< std::endl; fw.indent() << "autoRotateToScreen TRUE"<< std::endl;
} }
if (text.getAutoScaleToLimitScreenSizeToFontResolution())
{
fw.indent() << "autoScaleToLimitScreenSizeToFontResolution TRUE"<< std::endl;
}
// layout // layout
fw.indent() << "layout "; fw.indent() << "layout ";

View File

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

View File

@ -199,7 +199,7 @@ bool OSGPageManager::StartThread(ThreadMode mode,ThreadID &newThread)
DWORD dwThreadId=0; DWORD dwThreadId=0;
LPVOID dwThrdParam = (LPVOID) this; LPVOID dwThrdParam = (LPVOID) this;
newThread = CreateThread( threadID = newThread = CreateThread(
NULL, // default security attributes NULL, // default security attributes
0, // use default stack size 0, // use default stack size
ThreadFunc, // thread function ThreadFunc, // thread function
@ -223,6 +223,7 @@ bool OSGPageManager::StartThread(ThreadMode mode,ThreadID &newThread)
threadMode = mode; threadMode = mode;
if( pthread_create( &newThread, 0L, ThreadFunc, (void *)this ) != 0 ) if( pthread_create( &newThread, 0L, ThreadFunc, (void *)this ) != 0 )
threadMode = ThreadNone; threadMode = ThreadNone;
threadID = newThread;
#endif #endif
return threadMode != ThreadNone; return threadMode != ThreadNone;
} }
@ -232,10 +233,18 @@ bool OSGPageManager::StartThread(ThreadMode mode,ThreadID &newThread)
*/ */
bool OSGPageManager::EndThread() bool OSGPageManager::EndThread()
{ {
cancel = true;
// claer the path for thred loop to finish
osgSetEvent(locationChangeEvent);
#ifdef _WIN32 #ifdef _WIN32
DWORD res = STILL_ACTIVE;
while(res==STILL_ACTIVE){
GetExitCodeThread(threadID,&res);
Sleep(100);
}
#else #else
// Need a handle to the thread ID here. // Need a handle to the thread ID here.
//pthread_cancel( ?newThread? ); pthread_join( threadID, 0 );
#endif #endif
return true; return true;
} }
@ -251,9 +260,10 @@ bool OSGPageManager::ThreadLoop()
if (threadMode != ThreadFree) if (threadMode != ThreadFree)
throw 1; throw 1;
bool done = false;
bool pagingActive = false; bool pagingActive = false;
while (!done) { cancel = false;
while (!cancel) {
/* Here's how we do it: /* Here's how we do it:
Wait for position change Wait for position change
Update manager w/ position Update manager w/ position
@ -308,10 +318,11 @@ bool OSGPageManager::ThreadLoop()
#endif #endif
// Now do a single load // Now do a single load
tile = pageManage->GetNextLoad(); 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; osg::Group *tileGroup=NULL;
pagingActive = false; pagingActive = false;
if (tile) {
osg::Group *parentNode = NULL; osg::Group *parentNode = NULL;
tileGroup = archive->LoadTile(NULL,pageManage,tile,&parentNode); tileGroup = archive->LoadTile(NULL,pageManage,tile,&parentNode);
pageManage->AckLoad(); pageManage->AckLoad();
@ -321,7 +332,9 @@ bool OSGPageManager::ThreadLoop()
// RO, commenting out as we don't want to do delete here, we want it to happen in the merge thread. // RO, commenting out as we don't want to do delete here, we want it to happen in the merge thread.
tileGroup->ref(); tileGroup->ref();
#endif #endif
} else { }
else
{
int x,y,lod; int x,y,lod;
tile->GetTileLoc(x,y,lod); tile->GetTileLoc(x,y,lod);
fprintf(stderr,"Failed to load tile (%d,%d,%d)\n",x,y,lod); fprintf(stderr,"Failed to load tile (%d,%d,%d)\n",x,y,lod);

View File

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

View File

@ -18,4 +18,11 @@ LIB = $(LIB_PREFIX)$(TARGET_BASENAME).$(LIB_EXT)
INC += $(PRODUCER_INCLUDE_DIR) -I/usr/X11R6/include INC += $(PRODUCER_INCLUDE_DIR) -I/usr/X11R6/include
LDFLAGS += $(PRODUCER_LIB_DIR) 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 include $(TOPDIR)/Make/makerules

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -41,7 +41,6 @@ LightPointDrawable::LightPointDrawable():
_colorMaskOff = new osg::ColorMask; _colorMaskOff = new osg::ColorMask;
_colorMaskOff->setMask(false,false,false,false); _colorMaskOff->setMask(false,false,false,false);
_point = new osg::Point;
} }
LightPointDrawable::LightPointDrawable(const LightPointDrawable& lpd,const osg::CopyOp& copyop): 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> _blendOne;
osg::ref_ptr<osg::BlendFunc> _blendOneMinusSrcAlpha; osg::ref_ptr<osg::BlendFunc> _blendOneMinusSrcAlpha;
osg::ref_ptr<osg::ColorMask> _colorMaskOff; osg::ref_ptr<osg::ColorMask> _colorMaskOff;
osg::ref_ptr<osg::Point> _point;
}; };

View File

@ -24,13 +24,29 @@
#include <typeinfo> #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(): LightPointNode::LightPointNode():
_minPixelSize(0.0f), _minPixelSize(0.0f),
_maxPixelSize(30.0f), _maxPixelSize(30.0f),
_maxVisableDistance2(FLT_MAX) _maxVisableDistance2(FLT_MAX)
{ {
setStateSet(getSingletonLightPointStateSet());
} }
/** Copy constructor using CopyOp to manage deep vs shallow copy.*/ /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
@ -66,6 +82,12 @@ bool LightPointNode::computeBound() const
_bsphere.init(); _bsphere.init();
_bbox.init(); _bbox.init();
if (_lightPointList.empty())
{
_bsphere_computed=true;
return false;
}
LightPointList::const_iterator itr; LightPointList::const_iterator itr;
for(itr=_lightPointList.begin(); for(itr=_lightPointList.begin();
@ -96,6 +118,12 @@ bool LightPointNode::computeBound() const
void LightPointNode::traverse(osg::NodeVisitor& nv) void LightPointNode::traverse(osg::NodeVisitor& nv)
{ {
if (_lightPointList.empty())
{
// no light points so no op.
return;
}
//#define USE_TIMER //#define USE_TIMER
#ifdef USE_TIMER #ifdef USE_TIMER
osg::Timer 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 /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
* *
* This library is open source and may be redistributed and/or modified under * This library is open source and may be redistributed and/or modified under
@ -459,6 +460,20 @@ 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. // now subload the glyphs that are outstanding for this graphics context.
GlyphPtrList& glyphsWereSubloading = _glyphsToSubload[contextID]; GlyphPtrList& glyphsWereSubloading = _glyphsToSubload[contextID];
@ -466,6 +481,12 @@ void Font::GlyphTexture::apply(osg::State& state) const
if (!glyphsWereSubloading.empty()) if (!glyphsWereSubloading.empty())
{ {
if (!s_subloadAllGlyphsTogether)
{
// default way of subloading as required.
//std::cout<<"subloading"<<std::endl;
for(GlyphPtrList::iterator itr=glyphsWereSubloading.begin(); for(GlyphPtrList::iterator itr=glyphsWereSubloading.begin();
itr!=glyphsWereSubloading.end(); itr!=glyphsWereSubloading.end();
++itr) ++itr)
@ -475,6 +496,59 @@ void Font::GlyphTexture::apply(osg::State& state) const
// clear the list since we have now subloaded them. // clear the list since we have now subloaded them.
glyphsWereSubloading.clear(); 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;
}
} }
else else
{ {
@ -556,7 +630,7 @@ void Font::Glyph::subload() const
"\t "<<s()<<" ,"<<t()<<std::endl<<hex<< "\t "<<s()<<" ,"<<t()<<std::endl<<hex<<
"\t 0x"<<(GLenum)getPixelFormat()<<std::endl<< "\t 0x"<<(GLenum)getPixelFormat()<<std::endl<<
"\t 0x"<<(GLenum)getDataType()<<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; 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(): Text::Text():
_fontWidth(32), _fontWidth(32),
_fontHeight(32), _fontHeight(32),
_characterHeight(32), _characterHeight(32),
_characterAspectRatio(1.0f), _characterAspectRatio(1.0f),
_characterSizeMode(OBJECT_COORDS),
_maximumWidth(0.0f), _maximumWidth(0.0f),
_maximumHeight(0.0f), _maximumHeight(0.0f),
_alignment(BASE_LINE), _alignment(BASE_LINE),
_autoUpdateEyeMovementTolerance(0.0f),
_autoRotateToScreen(false), _autoRotateToScreen(false),
_autoScaleToLimitScreenSizeToFontResolution(false),
_layout(LEFT_TO_RIGHT), _layout(LEFT_TO_RIGHT),
_color(1.0f,1.0f,1.0f,1.0f), _color(1.0f,1.0f,1.0f,1.0f),
_drawMode(TEXT) _drawMode(TEXT)
{ {
setUseDisplayList(false); setUseDisplayList(false);
setScale(1.0f);
} }
Text::Text(const Text& text,const osg::CopyOp& copyop): 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), _fontHeight(text._fontHeight),
_characterHeight(text._characterHeight), _characterHeight(text._characterHeight),
_characterAspectRatio(text._characterAspectRatio), _characterAspectRatio(text._characterAspectRatio),
_characterSizeMode(text._characterSizeMode),
_maximumWidth(text._maximumWidth), _maximumWidth(text._maximumWidth),
_maximumHeight(text._maximumHeight), _maximumHeight(text._maximumHeight),
_text(text._text), _text(text._text),
_position(text._position), _position(text._position),
_alignment(text._alignment), _alignment(text._alignment),
_rotation(text._rotation), _rotation(text._rotation),
_scale(text._scale),
_autoUpdateEyeMovementTolerance(text._autoUpdateEyeMovementTolerance),
_autoRotateToScreen(text._autoRotateToScreen), _autoRotateToScreen(text._autoRotateToScreen),
_autoScaleToLimitScreenSizeToFontResolution(text._autoScaleToLimitScreenSizeToFontResolution),
_layout(text._layout), _layout(text._layout),
_color(text._color), _color(text._color),
_drawMode(text._drawMode) _drawMode(text._drawMode)
{ {
setUpAutoCallback();
computeGlyphRepresentation(); computeGlyphRepresentation();
} }
@ -189,7 +87,6 @@ void Text::setFontResolution(unsigned int width, unsigned int height)
computeGlyphRepresentation(); computeGlyphRepresentation();
} }
void Text::setCharacterSize(float height,float aspectRatio) void Text::setCharacterSize(float height,float aspectRatio)
{ {
_characterHeight = height; _characterHeight = height;
@ -278,75 +175,19 @@ void Text::setAxisAlignment(AxisAlignment axis)
void Text::setRotation(const osg::Quat& quat) void Text::setRotation(const osg::Quat& quat)
{ {
for(unsigned int i=0;i<_rotation.size();++i) _rotation = quat;
{ computePositions();
setRotation(i,quat);
}
} }
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) void Text::setAutoRotateToScreen(bool autoRotateToScreen)
{ {
if (_autoRotateToScreen==autoRotateToScreen) return; if (_autoRotateToScreen==autoRotateToScreen) return;
_autoRotateToScreen = autoRotateToScreen; _autoRotateToScreen = autoRotateToScreen;
setUpAutoCallback();
} }
void Text::setUpAutoCallback()
{
if (_autoRotateToScreen || _autoScaleToLimitScreenSizeToFontResolution)
{
if (!getCullCallback())
{
setCullCallback(new TextCullCallback(this));
}
}
else setCullCallback(0);
}
void Text::setLayout(Layout layout) void Text::setLayout(Layout layout)
{ {
if (_layout==layout) return; if (_layout==layout) return;
@ -369,7 +210,7 @@ void Text::setDrawMode(unsigned int mode)
_drawMode=mode; _drawMode=mode;
if (_drawMode&TEXT_PIXMAP) if (_drawMode&TEXT_PIXMAP)
{ {
setAutoScaleToLimitScreenSizeToFontResolution(true); setCharacterSizeMode(SCREEN_COORDS);
setAutoRotateToScreen(true); setAutoRotateToScreen(true);
} }
computeGlyphRepresentation(); computeGlyphRepresentation();
@ -388,9 +229,9 @@ bool Text::computeBound() const
if (_textBB.valid()) 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.xMin(),_textBB.yMin(),_textBB.zMin())*matrix);
_bbox.expandBy(osg::Vec3(_textBB.xMax(),_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); _bbox.expandBy(osg::Vec3(_textBB.xMax(),_textBB.yMax(),_textBB.zMin())*matrix);
@ -605,13 +446,13 @@ void Text::computeGlyphRepresentation()
void Text::computePositions() void Text::computePositions()
{ {
for(unsigned int i=0;i<_matrix.size();++i) for(unsigned int i=0;i<_autoTransformCache.size();++i)
{ {
computePositions(i); computePositions(i);
} }
} }
void Text::computePositions(unsigned int contextID) void Text::computePositions(unsigned int contextID) const
{ {
switch(_alignment) 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; case RIGHT_BASE_LINE: _offset.set((_textBB.xMax()+_textBB.xMin()),0.0f,0.0f); break;
} }
osg::Matrix& matrix = _matrix[contextID];
if (_scale[contextID]!=1.0f || !_rotation[contextID].zeroRotation())
AutoTransformCache& atc = _autoTransformCache[contextID];
osg::Matrix& matrix = atc._matrix;
if (_characterSizeMode!=OBJECT_COORDS || _autoRotateToScreen)
{ {
matrix.makeTranslate(-_offset); matrix.makeTranslate(-_offset);
if (_scale[contextID]!=1.0f) osg::Matrix rotate_matrix;
matrix.postMult(osg::Matrix::scale(_scale[contextID],_scale[contextID],_scale[contextID])); if (_autoRotateToScreen)
if (!_rotation[contextID].zeroRotation()) {
matrix.postMult(osg::Matrix::rotate(_rotation[contextID])); 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)); matrix.postMult(osg::Matrix::translate(_position));
} }
else else
@ -652,6 +567,7 @@ void Text::computePositions(unsigned int contextID)
} }
// now apply matrix to the glyphs. // now apply matrix to the glyphs.
for(TextureGlyphQuadMap::iterator titr=_textureGlyphQuadMap.begin(); for(TextureGlyphQuadMap::iterator titr=_textureGlyphQuadMap.begin();
titr!=_textureGlyphQuadMap.end(); titr!=_textureGlyphQuadMap.end();
@ -676,13 +592,60 @@ void Text::computePositions(unsigned int contextID)
_normal = osg::Matrix::transform3x3(osg::Vec3(0.0f,0.0f,1.0f),matrix); _normal = osg::Matrix::transform3x3(osg::Vec3(0.0f,0.0f,1.0f),matrix);
_normal.normalize(); _normal.normalize();
dirtyBound(); const_cast<Text*>(this)->dirtyBound();
} }
void Text::drawImplementation(osg::State& state) const void Text::drawImplementation(osg::State& state) const
{ {
unsigned int contextID = state.getContextID(); 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()); glNormal3fv(_normal.ptr());
glColor4fv(_color.ptr()); glColor4fv(_color.ptr());
@ -745,7 +708,7 @@ void Text::drawImplementation(osg::State& state) const
{ {
state.applyTextureMode(0,GL_TEXTURE_2D,osg::StateAttribute::OFF); 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 c00(osg::Vec3(_textBB.xMin(),_textBB.yMin(),_textBB.zMin())*matrix);
osg::Vec3 c10(osg::Vec3(_textBB.xMax(),_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); 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 hl(osg::Vec3(_offset.x()-cursorsize,_offset.y(),_offset.z())*matrix);
osg::Vec3 hr(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.setVertexArray(glyphquad._transformedCoords[0].size(),&(glyphquad._transformedCoords[0].front()));
pf.drawArrays(GL_QUADS,0,glyphquad._transformedCoords[0].size()); 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) if (geometry)
{ {
osg::Vec3Array* vertices = geometry->getVertexArray(); osg::Vec3Array* vertices = dynamic_cast<osg::Vec3Array*>(geometry->getVertexArray());
if (vertices) if (vertices)
{ {
osg::Vec3* first = &(vertices->front()); osg::Vec3* first = &(vertices->front());

View File

@ -13,6 +13,7 @@
#include <osgUtil/Optimizer> #include <osgUtil/Optimizer>
#include <osg/Transform> #include <osg/Transform>
#include <osg/TransformAttributeFunctor>
#include <osg/MatrixTransform> #include <osg/MatrixTransform>
#include <osg/PositionAttitudeTransform> #include <osg/PositionAttitudeTransform>
#include <osg/LOD> #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 // Optimize State Visitor
@ -535,7 +497,7 @@ void CollectLowestTransformsVisitor::doTransform(osg::Object* obj,osg::Matrix& m
osg::Drawable* drawable = dynamic_cast<osg::Drawable*>(obj); osg::Drawable* drawable = dynamic_cast<osg::Drawable*>(obj);
if (drawable) if (drawable)
{ {
TransformFunctor tf(matrix); osg::TransformAttributeFunctor tf(matrix);
drawable->accept(tf); drawable->accept(tf);
drawable->dirtyBound(); drawable->dirtyBound();
return; return;
@ -570,7 +532,7 @@ void CollectLowestTransformsVisitor::doTransform(osg::Object* obj,osg::Matrix& m
osg::Matrix matrix_no_trans = matrix; osg::Matrix matrix_no_trans = matrix;
matrix_no_trans.setTrans(0.0f,0.0f,0.0f); 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()); osg::Vec3 axis = osg::Matrix::transform3x3(tf._im,billboard->getAxis());
axis.normalize(); axis.normalize();
@ -1362,14 +1324,62 @@ bool Optimizer::MergeGeometryVisitor::geometryContainsSharedArrays(osg::Geometry
return false; 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) bool Optimizer::MergeGeometryVisitor::mergeGeometry(osg::Geometry& lhs,osg::Geometry& rhs)
{ {
MergeArrayVisitor merger;
unsigned int base = 0; unsigned int base = 0;
if (lhs.getVertexArray() && rhs.getVertexArray()) 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()) 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) 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()) 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) if (lhs.getColorArray() && rhs.getColorArray() && lhs.getColorBinding()!=osg::Geometry::BIND_OVERALL)
{ {
// we need to add the handling of the other array types... merger.merge(lhs.getColorArray(),rhs.getColorArray());
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());
}
} }
else if (rhs.getColorArray()) else if (rhs.getColorArray())
{ {
lhs.setColorArray(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) for(unsigned int unit=0;unit<lhs.getNumTexCoordArrays();++unit)
{ {
// we need to add the handling of the other array types... merger.merge(lhs.getTexCoordArray(unit),rhs.getTexCoordArray(unit));
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());
}
} }
// shift the indices of the incomming primitives to account for the pre exisiting geometry. // 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() 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; _globalStateSet = new osg::StateSet;
_lightingMode=HEADLIGHT; _lightingMode=HEADLIGHT;

View File

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