1
0
mirror of https://bitbucket.org/librepilot/librepilot.git synced 2024-12-02 10:24:11 +01:00

Merge remote-tracking branch 'origin/next' into Brian-PipXtreme-V2

This commit is contained in:
Brian Webb 2012-03-20 20:55:55 -07:00
commit ca4d01b4f8
159 changed files with 6470 additions and 2237 deletions

2
.gitignore vendored
View File

@ -66,3 +66,5 @@ GPATH
GRTAGS GRTAGS
GSYMS GSYMS
GTAGS GTAGS
/.cproject
/.project

View File

@ -0,0 +1 @@
/qrc_glc_lib.cpp

View File

@ -30,6 +30,8 @@
/*! /*!
* \defgroup light Lights * \defgroup light Lights
*/ */
/*!
/*! /*!
* \ingroup light * \ingroup light

View File

@ -28,7 +28,6 @@
// Class chunk id // Class chunk id
quint32 GLC_3DRep::m_ChunkId= 0xA702; quint32 GLC_3DRep::m_ChunkId= 0xA702;
// Default constructor
GLC_3DRep::GLC_3DRep() GLC_3DRep::GLC_3DRep()
: GLC_Rep() : GLC_Rep()
, m_pGeomList(new QList<GLC_Geometry*>) , m_pGeomList(new QList<GLC_Geometry*>)
@ -37,7 +36,6 @@ GLC_3DRep::GLC_3DRep()
} }
// Construct a 3DRep with a geometry
GLC_3DRep::GLC_3DRep(GLC_Geometry* pGeom) GLC_3DRep::GLC_3DRep(GLC_Geometry* pGeom)
: GLC_Rep() : GLC_Rep()
, m_pGeomList(new QList<GLC_Geometry*>) , m_pGeomList(new QList<GLC_Geometry*>)
@ -48,7 +46,6 @@ GLC_3DRep::GLC_3DRep(GLC_Geometry* pGeom)
setName(pGeom->name()); setName(pGeom->name());
} }
// Copy Constructor
GLC_3DRep::GLC_3DRep(const GLC_3DRep& rep) GLC_3DRep::GLC_3DRep(const GLC_3DRep& rep)
: GLC_Rep(rep) : GLC_Rep(rep)
, m_pGeomList(rep.m_pGeomList) , m_pGeomList(rep.m_pGeomList)
@ -57,7 +54,6 @@ GLC_3DRep::GLC_3DRep(const GLC_3DRep& rep)
} }
// Assignement operator
GLC_3DRep& GLC_3DRep::operator=(const GLC_Rep& rep) GLC_3DRep& GLC_3DRep::operator=(const GLC_Rep& rep)
{ {
const GLC_3DRep* p3DRep= dynamic_cast<const GLC_3DRep*>(&rep); const GLC_3DRep* p3DRep= dynamic_cast<const GLC_3DRep*>(&rep);
@ -73,13 +69,11 @@ GLC_3DRep& GLC_3DRep::operator=(const GLC_Rep& rep)
return *this; return *this;
} }
// Clone the representation
GLC_Rep* GLC_3DRep::clone() const GLC_Rep* GLC_3DRep::clone() const
{ {
return new GLC_3DRep(*this); return new GLC_3DRep(*this);
} }
// Make a deep copy of the 3DRep
GLC_Rep* GLC_3DRep::deepCopy() const GLC_Rep* GLC_3DRep::deepCopy() const
{ {
GLC_3DRep* pCloneRep= new GLC_3DRep; GLC_3DRep* pCloneRep= new GLC_3DRep;
@ -95,7 +89,6 @@ GLC_Rep* GLC_3DRep::deepCopy() const
return pCloneRep; return pCloneRep;
} }
// Destructor
GLC_3DRep::~GLC_3DRep() GLC_3DRep::~GLC_3DRep()
{ {
clear(); clear();
@ -104,13 +97,11 @@ GLC_3DRep::~GLC_3DRep()
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Get functions // Get functions
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Return the class Chunk ID
quint32 GLC_3DRep::chunckID() quint32 GLC_3DRep::chunckID()
{ {
return m_ChunkId; return m_ChunkId;
} }
// Return the type of representation
int GLC_3DRep::type() const int GLC_3DRep::type() const
{ {
return (*m_pType); return (*m_pType);
@ -120,7 +111,6 @@ int GLC_3DRep::type() const
// Get functions // Get functions
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Return true if the rep bounding box is valid
bool GLC_3DRep::boundingBoxIsValid() const bool GLC_3DRep::boundingBoxIsValid() const
{ {
bool result= !m_pGeomList->isEmpty(); bool result= !m_pGeomList->isEmpty();
@ -134,7 +124,6 @@ bool GLC_3DRep::boundingBoxIsValid() const
return result; return result;
} }
// Return the 3DRep bounding Box
GLC_BoundingBox GLC_3DRep::boundingBox() const GLC_BoundingBox GLC_3DRep::boundingBox() const
{ {
GLC_BoundingBox resultBox; GLC_BoundingBox resultBox;
@ -146,7 +135,6 @@ GLC_BoundingBox GLC_3DRep::boundingBox() const
return resultBox; return resultBox;
} }
// Get number of faces
unsigned int GLC_3DRep::faceCount() const unsigned int GLC_3DRep::faceCount() const
{ {
unsigned int result= 0; unsigned int result= 0;
@ -162,7 +150,6 @@ unsigned int GLC_3DRep::faceCount() const
return result; return result;
} }
// Get number of vertex
unsigned int GLC_3DRep::vertexCount() const unsigned int GLC_3DRep::vertexCount() const
{ {
unsigned int result= 0; unsigned int result= 0;
@ -178,7 +165,6 @@ unsigned int GLC_3DRep::vertexCount() const
return result; return result;
} }
// Get number of materials
unsigned int GLC_3DRep::materialCount() const unsigned int GLC_3DRep::materialCount() const
{ {
unsigned int result= 0; unsigned int result= 0;
@ -194,7 +180,6 @@ unsigned int GLC_3DRep::materialCount() const
return result; return result;
} }
// Get materials List
QSet<GLC_Material*> GLC_3DRep::materialSet() const QSet<GLC_Material*> GLC_3DRep::materialSet() const
{ {
QSet<GLC_Material*> result; QSet<GLC_Material*> result;
@ -210,7 +195,18 @@ QSet<GLC_Material*> GLC_3DRep::materialSet() const
return result; return result;
} }
// Remove empty geometries double GLC_3DRep::volume() const
{
double resultVolume= 0.0;
const int geomCount= m_pGeomList->count();
for (int i= 0; i < geomCount; ++i)
{
resultVolume+= m_pGeomList->at(i)->volume();
}
return resultVolume;
}
void GLC_3DRep::clean() void GLC_3DRep::clean()
{ {
QList<GLC_Geometry*>::iterator iGeomList= m_pGeomList->begin(); QList<GLC_Geometry*>::iterator iGeomList= m_pGeomList->begin();
@ -229,7 +225,6 @@ void GLC_3DRep::clean()
} }
} }
// Reverse geometries normals
void GLC_3DRep::reverseNormals() void GLC_3DRep::reverseNormals()
{ {
const int size= m_pGeomList->size(); const int size= m_pGeomList->size();
@ -239,7 +234,6 @@ void GLC_3DRep::reverseNormals()
} }
} }
// Load the representation
bool GLC_3DRep::load() bool GLC_3DRep::load()
{ {
bool loadSucces= false; bool loadSucces= false;
@ -274,7 +268,7 @@ bool GLC_3DRep::load()
return loadSucces; return loadSucces;
} }
// Replace the representation
void GLC_3DRep::replace(GLC_Rep* pRep) void GLC_3DRep::replace(GLC_Rep* pRep)
{ {
GLC_3DRep* p3DRep= dynamic_cast<GLC_3DRep*>(pRep); GLC_3DRep* p3DRep= dynamic_cast<GLC_3DRep*>(pRep);
@ -295,7 +289,6 @@ void GLC_3DRep::replace(GLC_Rep* pRep)
} }
} }
// Replace the specified material by a new one
void GLC_3DRep::replaceMaterial(GLC_uint oldId, GLC_Material* pNewMaterial) void GLC_3DRep::replaceMaterial(GLC_uint oldId, GLC_Material* pNewMaterial)
{ {
//qDebug() << "GLC_3DRep::replaceMaterial"; //qDebug() << "GLC_3DRep::replaceMaterial";
@ -315,7 +308,6 @@ void GLC_3DRep::replaceMaterial(GLC_uint oldId, GLC_Material* pNewMaterial)
} }
} }
// Merge this 3Drep with another 3DRep
void GLC_3DRep::merge(const GLC_3DRep* pRep) void GLC_3DRep::merge(const GLC_3DRep* pRep)
{ {
// Get the number of geometry of pRep // Get the number of geometry of pRep
@ -361,7 +353,6 @@ void GLC_3DRep::transformSubGeometries(const GLC_Matrix4x4& matrix)
{ {
// Get the number of geometry of pRep // Get the number of geometry of pRep
const int repCount= m_pGeomList->size(); const int repCount= m_pGeomList->size();
qDebug() << "repCount " << repCount;
for (int i= 0; i < repCount; ++i) for (int i= 0; i < repCount; ++i)
{ {
GLC_Mesh* pCurrentMesh= dynamic_cast<GLC_Mesh*>(geomAt(i)); GLC_Mesh* pCurrentMesh= dynamic_cast<GLC_Mesh*>(geomAt(i));
@ -372,7 +363,16 @@ void GLC_3DRep::transformSubGeometries(const GLC_Matrix4x4& matrix)
} }
} }
// UnLoad the representation void GLC_3DRep::setVboUsage(bool usage)
{
// Get the number of geometry of pRep
const int repCount= m_pGeomList->size();
for (int i= 0; i < repCount; ++i)
{
m_pGeomList->at(i)->setVboUsage(usage);
}
}
bool GLC_3DRep::unload() bool GLC_3DRep::unload()
{ {
bool unloadSucess= false; bool unloadSucess= false;
@ -404,7 +404,6 @@ bool GLC_3DRep::unload()
// private services functions // private services functions
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Clear the 3D representation
void GLC_3DRep::clear() void GLC_3DRep::clear()
{ {
if (isTheLast()) if (isTheLast())
@ -422,7 +421,6 @@ void GLC_3DRep::clear()
} }
} }
// Non Member methods // Non Member methods
// Non-member stream operator
QDataStream &operator<<(QDataStream & stream, const GLC_3DRep & rep) QDataStream &operator<<(QDataStream & stream, const GLC_3DRep & rep)
{ {
quint32 chunckId= GLC_3DRep::m_ChunkId; quint32 chunckId= GLC_3DRep::m_ChunkId;
@ -457,6 +455,7 @@ QDataStream &operator<<(QDataStream & stream, const GLC_3DRep & rep)
return stream; return stream;
} }
QDataStream &operator>>(QDataStream & stream, GLC_3DRep & rep) QDataStream &operator>>(QDataStream & stream, GLC_3DRep & rep)
{ {
Q_ASSERT(rep.isEmpty()); Q_ASSERT(rep.isEmpty());

View File

@ -121,6 +121,9 @@ public:
//! Return materials Set of this 3DRep //! Return materials Set of this 3DRep
QSet<GLC_Material*> materialSet() const; QSet<GLC_Material*> materialSet() const;
//! Return the volume of this 3DRep
double volume() const;
//@} //@}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -168,6 +171,8 @@ public:
//! Transform 3DRep sub mesh vertice with the given matrix //! Transform 3DRep sub mesh vertice with the given matrix
void transformSubGeometries(const GLC_Matrix4x4& matrix); void transformSubGeometries(const GLC_Matrix4x4& matrix);
//! Set VBO usage
void setVboUsage(bool usage);
//@} //@}

View File

@ -36,7 +36,7 @@ GLC_Box::GLC_Box(double dLx, double dLy, double dlz)
, m_dLgY(dLy) , m_dLgY(dLy)
, m_dLgZ(dlz) , m_dLgZ(dlz)
{ {
createMeshAndWire();
} }
// Copy constructor // Copy constructor
GLC_Box::GLC_Box(const GLC_Box& box) GLC_Box::GLC_Box(const GLC_Box& box)
@ -45,7 +45,7 @@ GLC_Box::GLC_Box(const GLC_Box& box)
, m_dLgY(box.m_dLgY) , m_dLgY(box.m_dLgY)
, m_dLgZ(box.m_dLgZ) , m_dLgZ(box.m_dLgZ)
{ {
createMeshAndWire();
} }
GLC_Box::~GLC_Box() GLC_Box::~GLC_Box()
{ {

View File

@ -32,7 +32,7 @@ const QString GLC_BSRep::m_Suffix("BSRep");
const QUuid GLC_BSRep::m_Uuid("{d6f97789-36a9-4c2e-b667-0e66c27f839f}"); const QUuid GLC_BSRep::m_Uuid("{d6f97789-36a9-4c2e-b667-0e66c27f839f}");
// The binary rep version // The binary rep version
const quint32 GLC_BSRep::m_Version= 102; const quint32 GLC_BSRep::m_Version= 103;
// Mutex used by compression // Mutex used by compression
QMutex GLC_BSRep::m_CompressionMutex; QMutex GLC_BSRep::m_CompressionMutex;
@ -181,6 +181,11 @@ QString GLC_BSRep::suffix()
return m_Suffix; return m_Suffix;
} }
quint32 GLC_BSRep::version()
{
return m_Version;
}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
//name Set Functions //name Set Functions
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -322,7 +327,7 @@ bool GLC_BSRep::headerIsOk()
// Set the version of the data stream // Set the version of the data stream
m_DataStream.setVersion(QDataStream::Qt_4_6); m_DataStream.setVersion(QDataStream::Qt_4_6);
bool headerOk= (uuid == m_Uuid) && (version == m_Version) && writeFinished; bool headerOk= (uuid == m_Uuid) && (version <= m_Version) && (version > 101) && writeFinished;
return headerOk; return headerOk;
} }

View File

@ -75,6 +75,9 @@ public:
//! Return bsrep suffix //! Return bsrep suffix
static QString suffix(); static QString suffix();
//! Return bsrep version
static quint32 version();
//@} //@}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////

View File

@ -33,6 +33,7 @@ GLC_Cone::GLC_Cone(double dRadius, double dLength)
, m_Discret(glc::GLC_POLYDISCRET) // Default discretion , m_Discret(glc::GLC_POLYDISCRET) // Default discretion
{ {
Q_ASSERT((m_Radius > 0.0) && (m_Length > 0.0)); Q_ASSERT((m_Radius > 0.0) && (m_Length > 0.0));
createMeshAndWire();
} }
GLC_Cone::GLC_Cone(const GLC_Cone& sourceCone) GLC_Cone::GLC_Cone(const GLC_Cone& sourceCone)
@ -41,7 +42,7 @@ GLC_Cone::GLC_Cone(const GLC_Cone& sourceCone)
, m_Length(sourceCone.m_Length) , m_Length(sourceCone.m_Length)
, m_Discret(sourceCone.m_Discret) , m_Discret(sourceCone.m_Discret)
{ {
createMeshAndWire();
} }
GLC_Cone::~GLC_Cone() GLC_Cone::~GLC_Cone()

View File

@ -44,6 +44,7 @@ GLC_Cylinder::GLC_Cylinder(double dRadius, double dLength)
, m_EndedIsCaped(true) // Cylinder ended are closed , m_EndedIsCaped(true) // Cylinder ended are closed
{ {
Q_ASSERT((m_Radius > 0.0) && (m_Length > 0.0)); Q_ASSERT((m_Radius > 0.0) && (m_Length > 0.0));
createMeshAndWire();
} }
GLC_Cylinder::GLC_Cylinder(const GLC_Cylinder& sourceCylinder) GLC_Cylinder::GLC_Cylinder(const GLC_Cylinder& sourceCylinder)
@ -54,6 +55,7 @@ GLC_Cylinder::GLC_Cylinder(const GLC_Cylinder& sourceCylinder)
, m_EndedIsCaped(sourceCylinder.m_EndedIsCaped) , m_EndedIsCaped(sourceCylinder.m_EndedIsCaped)
{ {
Q_ASSERT((m_Radius > 0.0) && (m_Length > 0.0) && (m_Discret > 0)); Q_ASSERT((m_Radius > 0.0) && (m_Length > 0.0) && (m_Discret > 0));
createMeshAndWire();
} }
GLC_Cylinder::~GLC_Cylinder() GLC_Cylinder::~GLC_Cylinder()

View File

@ -30,7 +30,7 @@ GLC_Disc::GLC_Disc(double radius, double angle)
, m_Angle(angle) , m_Angle(angle)
, m_Step(0) , m_Step(0)
{ {
createMeshAndWire();
} }
GLC_Disc::GLC_Disc(const GLC_Disc& disc) GLC_Disc::GLC_Disc(const GLC_Disc& disc)
@ -40,7 +40,7 @@ GLC_Disc::GLC_Disc(const GLC_Disc& disc)
, m_Angle(disc.m_Angle) , m_Angle(disc.m_Angle)
, m_Step(disc.m_Step) , m_Step(disc.m_Step)
{ {
createMeshAndWire();
} }
GLC_Disc::~GLC_Disc() GLC_Disc::~GLC_Disc()

View File

@ -25,6 +25,7 @@
#include "../shading/glc_selectionmaterial.h" #include "../shading/glc_selectionmaterial.h"
#include "../glc_openglexception.h" #include "../glc_openglexception.h"
#include "../glc_state.h" #include "../glc_state.h"
#include "../glc_context.h"
#include "glc_geometry.h" #include "glc_geometry.h"
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -44,6 +45,7 @@ GLC_Geometry::GLC_Geometry(const QString& name, const bool typeIsWire)
, m_TransparentMaterialNumber(0) , m_TransparentMaterialNumber(0)
, m_Id(glc::GLC_GenGeomID()) , m_Id(glc::GLC_GenGeomID())
, m_Name(name) , m_Name(name)
, m_UseVbo(false)
{ {
} }
@ -61,6 +63,7 @@ GLC_Geometry::GLC_Geometry(const GLC_Geometry& sourceGeom)
, m_TransparentMaterialNumber(sourceGeom.m_TransparentMaterialNumber) , m_TransparentMaterialNumber(sourceGeom.m_TransparentMaterialNumber)
, m_Id(glc::GLC_GenGeomID()) , m_Id(glc::GLC_GenGeomID())
, m_Name(sourceGeom.m_Name) , m_Name(sourceGeom.m_Name)
, m_UseVbo(sourceGeom.m_UseVbo)
{ {
// Add this mesh to inner material // Add this mesh to inner material
MaterialHash::const_iterator i= sourceGeom.m_MaterialHash.constBegin(); MaterialHash::const_iterator i= sourceGeom.m_MaterialHash.constBegin();
@ -95,6 +98,7 @@ GLC_Geometry& GLC_Geometry::operator=(const GLC_Geometry& sourceGeom)
m_TransparentMaterialNumber= sourceGeom.m_TransparentMaterialNumber; m_TransparentMaterialNumber= sourceGeom.m_TransparentMaterialNumber;
m_Id= glc::GLC_GenGeomID(); m_Id= glc::GLC_GenGeomID();
m_Name= sourceGeom.m_Name; m_Name= sourceGeom.m_Name;
m_UseVbo= sourceGeom.m_UseVbo;
} }
return *this; return *this;
} }
@ -134,6 +138,11 @@ unsigned int GLC_Geometry::VertexCount() const
return 0; return 0;
} }
double GLC_Geometry::volume()
{
return 0.0;
}
///////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////
// Set Functions // Set Functions
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -179,7 +188,6 @@ void GLC_Geometry::updateTransparentMaterialNumber()
} }
if (m_WireColor.alpha() != 255) if (m_WireColor.alpha() != 255)
{ {
qDebug() << "GLC_Geometry::updateTransparentMaterialNumber()";
++m_TransparentMaterialNumber; ++m_TransparentMaterialNumber;
} }
} }
@ -187,8 +195,6 @@ void GLC_Geometry::updateTransparentMaterialNumber()
// Add material to mesh // Add material to mesh
void GLC_Geometry::addMaterial(GLC_Material* pMaterial) void GLC_Geometry::addMaterial(GLC_Material* pMaterial)
{ {
Q_ASSERT(!m_IsWire);
if (pMaterial != NULL) if (pMaterial != NULL)
{ {
const GLC_uint materialID= pMaterial->id(); const GLC_uint materialID= pMaterial->id();
@ -234,6 +240,15 @@ void GLC_Geometry::releaseVboClientSide(bool update)
m_WireData.releaseVboClientSide(update); m_WireData.releaseVboClientSide(update);
} }
void GLC_Geometry::setVboUsage(bool usage)
{
m_UseVbo= usage;
if (!usage || (usage && GLC_State::vboSupported()))
{
m_WireData.setVboUsage(m_UseVbo);
}
}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// OpenGL Functions // OpenGL Functions
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -283,7 +298,7 @@ void GLC_Geometry::render(const GLC_RenderProperties& renderProperties)
GLenum error= glGetError(); GLenum error= glGetError();
if (error != GL_NO_ERROR) if (error != GL_NO_ERROR)
{ {
GLC_OpenGlException OpenGlException("GLC_Geometry::glExecute " + name(), error); GLC_OpenGlException OpenGlException("GLC_Geometry::render " + name(), error);
throw(OpenGlException); throw(OpenGlException);
} }
} }
@ -297,7 +312,7 @@ void GLC_Geometry::glPropGeom(const GLC_RenderProperties& renderProperties)
if(m_IsWire) if(m_IsWire)
{ {
glLineWidth(m_LineWidth); glLineWidth(m_LineWidth);
glDisable(GL_LIGHTING); GLC_Context::current()->glcEnableLighting(false);;
if (!renderProperties.isSelected()) if (!renderProperties.isSelected())
{ {
// Set polyline colors // Set polyline colors
@ -318,13 +333,13 @@ void GLC_Geometry::glPropGeom(const GLC_RenderProperties& renderProperties)
GLC_Material* pCurrentMaterial= m_MaterialHash.begin().value(); GLC_Material* pCurrentMaterial= m_MaterialHash.begin().value();
if (pCurrentMaterial->hasTexture()) if (pCurrentMaterial->hasTexture())
{ {
glEnable(GL_LIGHTING); GLC_Context::current()->glcEnableLighting(true);
pCurrentMaterial->glExecute(); pCurrentMaterial->glExecute();
if (renderProperties.isSelected()) GLC_SelectionMaterial::glExecute(); if (renderProperties.isSelected()) GLC_SelectionMaterial::glExecute();
} }
else else
{ {
glEnable(GL_LIGHTING); GLC_Context::current()->glcEnableLighting(true);
if (renderProperties.isSelected()) GLC_SelectionMaterial::glExecute(); if (renderProperties.isSelected()) GLC_SelectionMaterial::glExecute();
else pCurrentMaterial->glExecute(); else pCurrentMaterial->glExecute();
} }

View File

@ -29,7 +29,7 @@
#include "glc_wiredata.h" #include "glc_wiredata.h"
#include "../glc_boundingbox.h" #include "../glc_boundingbox.h"
#include "glc_config.h" #include "../glc_config.h"
typedef QHash<GLC_uint, GLC_Material*> MaterialHash; typedef QHash<GLC_uint, GLC_Material*> MaterialHash;
typedef QHash<GLC_uint, GLC_uint> MaterialHashMap; typedef QHash<GLC_uint, GLC_uint> MaterialHashMap;
@ -68,19 +68,13 @@ class GLC_LIB_EXPORT GLC_Geometry
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
public: public:
//! Default constructor //! Default constructor
/*! GLC_Geometry(const QString &name, const bool type);
* QString Name
* const bool typeIsWire
*/
GLC_Geometry(const QString &, const bool);
//! Copy constructor //! Copy constructor
/*! GLC_Geometry(const GLC_Geometry& sourceGeom);
* const GLC_VboGeom geometry to copy
*/
GLC_Geometry(const GLC_Geometry&);
//! Overload "=" operator //! Overload "=" operator
GLC_Geometry& operator=(const GLC_Geometry&); GLC_Geometry& operator=(const GLC_Geometry& sourceGeom);
//! Destructor //! Destructor
virtual ~GLC_Geometry(); virtual ~GLC_Geometry();
@ -197,6 +191,13 @@ public:
inline GLsizei wirePolylineSize(int index) const inline GLsizei wirePolylineSize(int index) const
{return m_WireData.verticeGroupSize(index);} {return m_WireData.verticeGroupSize(index);}
//! Return the volume of this geometry
virtual double volume();
//! Return true if this geometry will try to use VBO
inline bool vboIsUsed() const
{return m_UseVbo;}
//@} //@}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -259,6 +260,9 @@ public:
//! Release client VBO //! Release client VBO
virtual void releaseVboClientSide(bool update= false); virtual void releaseVboClientSide(bool update= false);
//! Set VBO usage
virtual void setVboUsage(bool usage);
//@} //@}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
/*! \name OpenGL Functions*/ /*! \name OpenGL Functions*/
@ -357,6 +361,9 @@ private:
//! Name of geometry //! Name of geometry
QString m_Name; QString m_Name;
//! VBO usage flag
bool m_UseVbo;
}; };
#endif /*GLC_GEOMETRY_H_*/ #endif /*GLC_GEOMETRY_H_*/

View File

@ -28,19 +28,19 @@
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
GLC_Line::GLC_Line(const GLC_Point3d & point1, const GLC_Point3d & point2) GLC_Line::GLC_Line(const GLC_Point3d & point1, const GLC_Point3d & point2)
: GLC_Geometry("Line", true) : GLC_Polylines()
, m_Point1(point1) , m_Point1(point1)
, m_Point2(point2) , m_Point2(point2)
{ {
createWire();
} }
GLC_Line::GLC_Line(const GLC_Line& line) GLC_Line::GLC_Line(const GLC_Line& line)
: GLC_Geometry(line) : GLC_Polylines(line)
, m_Point1(line.m_Point1) , m_Point1(line.m_Point1)
, m_Point2(line.m_Point2) , m_Point2(line.m_Point2)
{ {
createWire();
} }
GLC_Line::~GLC_Line() GLC_Line::~GLC_Line()
@ -54,15 +54,7 @@ GLC_Line::~GLC_Line()
const GLC_BoundingBox& GLC_Line::boundingBox(void) const GLC_BoundingBox& GLC_Line::boundingBox(void)
{ {
return GLC_Polylines::boundingBox();
if (NULL == m_pBoundingBox)
{
m_pBoundingBox= new GLC_BoundingBox();
m_pBoundingBox->combine(m_Point1);
m_pBoundingBox->combine(m_Point2);
}
return *m_pBoundingBox;
} }
GLC_Geometry* GLC_Line::clone() const GLC_Geometry* GLC_Line::clone() const
@ -74,32 +66,44 @@ GLC_Geometry* GLC_Line::clone() const
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Set Functions // Set Functions
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
void GLC_Line::setColor(const QColor& color) void GLC_Line::setCoordinate(const GLC_Point3d &point1, const GLC_Point3d &point2)
{ {
m_WireColor= color; m_Point1= point1;
if (GLC_Geometry::hasMaterial()) m_Point2= point2;
{ clear();
GLC_Geometry::firstMaterial()->setDiffuseColor(color); createWire();
}
} }
GLC_Line& GLC_Line::operator=(const GLC_Line& line)
{
if (this != &line)
{
m_Point1= line.m_Point1;
m_Point2= line.m_Point2;
GLC_Polylines::operator=(line);
}
return *this;
}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// OpenGL Functions // OpenGL Functions
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
void GLC_Line::glDraw(const GLC_RenderProperties&) void GLC_Line::glDraw(const GLC_RenderProperties& renderProperties)
{ {
// Point Display GLC_Polylines::glDraw(renderProperties);
glBegin(GL_LINES);
glVertex3dv(m_Point1.data());
glVertex3dv(m_Point2.data());
glEnd();
// OpenGL error handler
GLenum error= glGetError();
if (error != GL_NO_ERROR)
{
GLC_OpenGlException OpenGlException("GLC_Line::GlDraw ", error);
throw(OpenGlException);
}
} }
//////////////////////////////////////////////////////////////////////
// Private services Functions
//////////////////////////////////////////////////////////////////////
void GLC_Line::createWire()
{
QList<GLC_Point3d> points;
points.append(m_Point1);
points.append(m_Point2);
GLC_Polylines::addPolyline(points);
}

View File

@ -23,7 +23,7 @@
#ifndef GLC_LINE_H_ #ifndef GLC_LINE_H_
#define GLC_LINE_H_ #define GLC_LINE_H_
#include "glc_geometry.h" #include "glc_polylines.h"
#include "../glc_config.h" #include "../glc_config.h"
@ -34,7 +34,7 @@
/*! An GLC_Line is just a simple renderable 3D Line*/ /*! An GLC_Line is just a simple renderable 3D Line*/
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
class GLC_LIB_EXPORT GLC_Line : public GLC_Geometry class GLC_LIB_EXPORT GLC_Line : public GLC_Polylines
{ {
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
/*! @name Constructor / Destructor */ /*! @name Constructor / Destructor */
@ -79,12 +79,15 @@ public:
//@{ //@{
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
public: public:
//! Set Line coordinate by 4D point //! Set Line coordinate by 3D point
void setCoordinate(const GLC_Point3d &, const GLC_Point3d &); void setCoordinate(const GLC_Point3d &point1, const GLC_Point3d &point2);
//! Set this line color //! Clear the content of this line Data and makes it empty
inline void setColor(const QColor& color); inline void clear()
{GLC_Polylines::clear();}
//! Set this line from the given line and return a reference of this line
GLC_Line& operator=(const GLC_Line& line);
//@} //@}
@ -100,6 +103,16 @@ private:
//@} //@}
//////////////////////////////////////////////////////////////////////
/*! \name Private services Functions*/
//@{
//////////////////////////////////////////////////////////////////////
private:
//! Create the wire
void createWire();
//@}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Private Member // Private Member
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////

View File

@ -22,7 +22,7 @@
//! \file glc_lod.cpp implementation of the GLC_Lod class. //! \file glc_lod.cpp implementation of the GLC_Lod class.
#include "../glc_exception.h"
#include "glc_lod.h" #include "glc_lod.h"
// Class chunk id // Class chunk id
@ -31,7 +31,7 @@ quint32 GLC_Lod::m_ChunkId= 0xA708;
GLC_Lod::GLC_Lod() GLC_Lod::GLC_Lod()
: m_Accuracy(0.0) : m_Accuracy(0.0)
, m_IboId(0) , m_IndexBuffer(QGLBuffer::IndexBuffer)
, m_IndexVector() , m_IndexVector()
, m_IndexSize(0) , m_IndexSize(0)
, m_TrianglesCount(0) , m_TrianglesCount(0)
@ -42,7 +42,7 @@ GLC_Lod::GLC_Lod()
GLC_Lod::GLC_Lod(double accuracy) GLC_Lod::GLC_Lod(double accuracy)
: m_Accuracy(accuracy) : m_Accuracy(accuracy)
, m_IboId(0) , m_IndexBuffer(QGLBuffer::IndexBuffer)
, m_IndexVector() , m_IndexVector()
, m_IndexSize(0) , m_IndexSize(0)
, m_TrianglesCount(0) , m_TrianglesCount(0)
@ -53,7 +53,7 @@ GLC_Lod::GLC_Lod(double accuracy)
GLC_Lod::GLC_Lod(const GLC_Lod& lod) GLC_Lod::GLC_Lod(const GLC_Lod& lod)
: m_Accuracy(lod.m_Accuracy) : m_Accuracy(lod.m_Accuracy)
, m_IboId(0) , m_IndexBuffer(QGLBuffer::IndexBuffer)
, m_IndexVector(lod.indexVector()) , m_IndexVector(lod.indexVector())
, m_IndexSize(lod.m_IndexSize) , m_IndexSize(lod.m_IndexSize)
, m_TrianglesCount(lod.m_TrianglesCount) , m_TrianglesCount(lod.m_TrianglesCount)
@ -68,7 +68,7 @@ GLC_Lod& GLC_Lod::operator=(const GLC_Lod& lod)
if (this != &lod) if (this != &lod)
{ {
m_Accuracy= lod.m_Accuracy; m_Accuracy= lod.m_Accuracy;
m_IboId= 0; m_IndexBuffer.destroy();
m_IndexVector= lod.indexVector(); m_IndexVector= lod.indexVector();
m_IndexSize= lod.m_IndexSize; m_IndexSize= lod.m_IndexSize;
m_TrianglesCount= lod.m_TrianglesCount; m_TrianglesCount= lod.m_TrianglesCount;
@ -79,11 +79,7 @@ GLC_Lod& GLC_Lod::operator=(const GLC_Lod& lod)
GLC_Lod::~GLC_Lod() GLC_Lod::~GLC_Lod()
{ {
// Delete IBO
if (0 != m_IboId)
{
glDeleteBuffers(1, &m_IboId);
}
} }
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -98,18 +94,18 @@ quint32 GLC_Lod::chunckID()
QVector<GLuint> GLC_Lod::indexVector() const QVector<GLuint> GLC_Lod::indexVector() const
{ {
if (0 != m_IboId) if (m_IndexBuffer.isCreated())
{ {
// VBO created get data from VBO // VBO created get data from VBO
const int sizeOfIbo= m_IndexSize; const int sizeOfIbo= m_IndexSize;
const GLsizeiptr dataSize= sizeOfIbo * sizeof(GLuint); const GLsizeiptr dataSize= sizeOfIbo * sizeof(GLuint);
QVector<GLuint> indexVector(sizeOfIbo); QVector<GLuint> indexVector(sizeOfIbo);
useIBO(); const_cast<QGLBuffer&>(m_IndexBuffer).bind();
GLvoid* pIbo = glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_READ_ONLY); GLvoid* pIbo = const_cast<QGLBuffer&>(m_IndexBuffer).map(QGLBuffer::ReadOnly);
memcpy(indexVector.data(), pIbo, dataSize); memcpy(indexVector.data(), pIbo, dataSize);
glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER); const_cast<QGLBuffer&>(m_IndexBuffer).unmap();
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); const_cast<QGLBuffer&>(m_IndexBuffer).release();
return indexVector; return indexVector;
} }
else else
@ -121,7 +117,7 @@ QVector<GLuint> GLC_Lod::indexVector() const
void GLC_Lod::copyIboToClientSide() void GLC_Lod::copyIboToClientSide()
{ {
if ((0 != m_IboId) && (m_IndexVector.isEmpty())) if (m_IndexBuffer.isCreated() && (m_IndexVector.isEmpty()))
{ {
m_IndexVector= indexVector(); m_IndexVector= indexVector();
} }
@ -130,22 +126,57 @@ void GLC_Lod::copyIboToClientSide()
void GLC_Lod::releaseIboClientSide(bool update) void GLC_Lod::releaseIboClientSide(bool update)
{ {
if((0 != m_IboId) && !m_IndexVector.isEmpty()) if(m_IndexBuffer.isCreated() && !m_IndexVector.isEmpty())
{ {
if (update) if (update)
{ {
// Copy index from client side to serveur // Copy index from client side to serveur
useIBO(); m_IndexBuffer.bind();
const GLsizei indexNbr= static_cast<GLsizei>(m_IndexVector.size()); const GLsizei indexNbr= static_cast<GLsizei>(m_IndexVector.size());
const GLsizeiptr indexSize = indexNbr * sizeof(GLuint); const GLsizeiptr indexSize = indexNbr * sizeof(GLuint);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexSize, m_IndexVector.data(), GL_STATIC_DRAW); m_IndexBuffer.allocate(m_IndexVector.data(), indexSize);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); m_IndexBuffer.release();
} }
m_IndexSize= m_IndexVector.size();
m_IndexVector.clear(); m_IndexVector.clear();
} }
} }
void GLC_Lod::setIboUsage(bool usage)
{
if (usage && !m_IndexVector.isEmpty())
{
createIBO();
// Copy index from client side to serveur
m_IndexBuffer.bind();
const GLsizei indexNbr= static_cast<GLsizei>(m_IndexVector.size());
const GLsizeiptr indexSize = indexNbr * sizeof(GLuint);
m_IndexBuffer.allocate(m_IndexVector.data(), indexSize);
m_IndexBuffer.release();
m_IndexSize= m_IndexVector.size();
m_IndexVector.clear();
}
else if (!usage && m_IndexBuffer.isCreated())
{
m_IndexVector= indexVector();
m_IndexBuffer.destroy();
}
}
void GLC_Lod::useIBO() const
{
Q_ASSERT(m_IndexBuffer.isCreated());
if (!const_cast<QGLBuffer&>(m_IndexBuffer).bind())
{
GLC_Exception exception("GLC_Lod::useIBO Failed to bind index buffer");
throw(exception);
}
}
QDataStream &operator<<(QDataStream &stream, const GLC_Lod &lod) QDataStream &operator<<(QDataStream &stream, const GLC_Lod &lod)
{ {

View File

@ -26,6 +26,8 @@
#define GLC_LOD_H_ #define GLC_LOD_H_
#include <QVector> #include <QVector>
#include <QGLBuffer>
#include "../glc_ext.h" #include "../glc_ext.h"
#include "../glc_config.h" #include "../glc_config.h"
@ -88,7 +90,7 @@ public:
* - Triangles Fans index * - Triangles Fans index
*/ */
inline QVector<GLuint>* indexVectorHandle() inline QVector<GLuint>* indexVectorHandle()
{ return &m_IndexVector;} {return &m_IndexVector;}
//! Return the size of the index Vector //! Return the size of the index Vector
inline int indexVectorSize() const inline int indexVectorSize() const
@ -111,12 +113,6 @@ public:
//! Release client IBO //! Release client IBO
void releaseIboClientSide(bool update= false); void releaseIboClientSide(bool update= false);
//! The mesh wich use this lod is finished
inline void finishVbo()
{
m_IndexSize= m_IndexVector.size();
m_IndexVector.clear();
}
//! Set accuracy of the LOD //! Set accuracy of the LOD
inline void setAccuracy(const double& accuracy) inline void setAccuracy(const double& accuracy)
{m_Accuracy= accuracy;} {m_Accuracy= accuracy;}
@ -127,6 +123,9 @@ public:
m_TrianglesCount+= count; m_TrianglesCount+= count;
} }
//! Set IBO usage
void setIboUsage(bool usage);
//@} //@}
@ -138,15 +137,18 @@ public:
//! IBO creation //! IBO creation
inline void createIBO() inline void createIBO()
{ {
if (0 == m_IboId && !m_IndexVector.isEmpty()) if (!m_IndexBuffer.isCreated() && !m_IndexVector.isEmpty())
{ {
glGenBuffers(1, &m_IboId); m_IndexBuffer.create();
} }
} }
//! Ibo Usage //! Ibo Usage
inline void useIBO() const void useIBO() const;
{glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IboId);}
//! Fill IBO
inline void fillIbo()
{releaseIboClientSide(true);}
//@} //@}
@ -158,8 +160,8 @@ private:
//! The accuracy of the LOD //! The accuracy of the LOD
double m_Accuracy; double m_Accuracy;
//! The IBO ID //! The Index Buffer
GLuint m_IboId; QGLBuffer m_IndexBuffer;
//! The Index Vector //! The Index Vector
QVector<GLuint> m_IndexVector; QVector<GLuint> m_IndexVector;

View File

@ -24,6 +24,7 @@
#include "glc_mesh.h" #include "glc_mesh.h"
#include "../glc_renderstatistics.h" #include "../glc_renderstatistics.h"
#include "../glc_context.h"
// Class chunk id // Class chunk id
quint32 GLC_Mesh::m_ChunkId= 0xA701; quint32 GLC_Mesh::m_ChunkId= 0xA701;
@ -167,7 +168,7 @@ const GLC_BoundingBox& GLC_Mesh::boundingBox()
if (m_MeshData.positionVectorHandle()->isEmpty()) if (m_MeshData.positionVectorHandle()->isEmpty())
{ {
qDebug() << "GLC_ExtendedMesh::getBoundingBox empty m_Positions"; qDebug() << "GLC_Mesh::boundingBox empty m_Positions";
} }
else else
{ {
@ -210,7 +211,7 @@ QVector<GLuint> GLC_Mesh::getTrianglesIndex(int lod, GLC_uint materialId) const
GLC_PrimitiveGroup* pPrimitiveGroup= m_PrimitiveGroups.value(lod)->value(materialId); GLC_PrimitiveGroup* pPrimitiveGroup= m_PrimitiveGroups.value(lod)->value(materialId);
int offset= 0; int offset= 0;
if (GLC_State::vboUsed()) if (vboIsUsed())
{ {
offset= static_cast<int>(reinterpret_cast<GLsizeiptr>(pPrimitiveGroup->trianglesIndexOffset()) / sizeof(GLuint)); offset= static_cast<int>(reinterpret_cast<GLsizeiptr>(pPrimitiveGroup->trianglesIndexOffset()) / sizeof(GLuint));
} }
@ -258,7 +259,7 @@ QList<QVector<GLuint> > GLC_Mesh::getStripsIndex(int lod, GLC_uint materialId) c
QList<int> sizes; QList<int> sizes;
int stripsCount; int stripsCount;
if (GLC_State::vboUsed()) if (vboIsUsed())
{ {
stripsCount= pPrimitiveGroup->stripsOffset().size(); stripsCount= pPrimitiveGroup->stripsOffset().size();
for (int i= 0; i < stripsCount; ++i) for (int i= 0; i < stripsCount; ++i)
@ -331,7 +332,7 @@ QList<QVector<GLuint> > GLC_Mesh::getFansIndex(int lod, GLC_uint materialId) con
QList<int> sizes; QList<int> sizes;
int fansCount; int fansCount;
if (GLC_State::vboUsed()) if (vboIsUsed())
{ {
fansCount= pPrimitiveGroup->fansOffset().size(); fansCount= pPrimitiveGroup->fansOffset().size();
for (int i= 0; i < fansCount; ++i) for (int i= 0; i < fansCount; ++i)
@ -455,6 +456,59 @@ GLC_Mesh& GLC_Mesh::transformVertice(const GLC_Matrix4x4& matrix)
return *this; return *this;
} }
double GLC_Mesh::volume()
{
double resultVolume= 0.0;
if (!m_MeshData.isEmpty())
{
IndexList triangleIndex;
QList<GLC_Material*> materials= materialSet().toList();
const int materialsCount= materials.count();
for (int i= 0; i < materialsCount; ++i)
{
GLC_uint materialId= materials.at(i)->id();
if (containsTriangles(0, materialId))
{
triangleIndex.append(getTrianglesIndex(0, materialId).toList());
}
if (containsStrips(0, materialId))
{
triangleIndex.append(equivalentTrianglesIndexOfstripsIndex(0, materialId));
}
if (containsFans(0, materialId))
{
triangleIndex.append(equivalentTrianglesIndexOfFansIndex(0, materialId));
}
}
GLfloatVector vertices= m_MeshData.positionVector();
Q_ASSERT((triangleIndex.count() % 3) == 0);
const int triangleCount= triangleIndex.count() / 3;
for (int i= 0; i < triangleCount; ++i)
{
const int index= i * 3;
const double v1x= vertices.at(triangleIndex.at(index) * 3);
const double v1y= vertices.at(triangleIndex.at(index) * 3 + 1);
const double v1z= vertices.at(triangleIndex.at(index) * 3 + 2);
const double v2x= vertices.at(triangleIndex.at(index + 1) * 3);
const double v2y= vertices.at(triangleIndex.at(index + 1) * 3 + 1);
const double v2z= vertices.at(triangleIndex.at(index + 1) * 3 + 2);
const double v3x= vertices.at(triangleIndex.at(index + 2) * 3);
const double v3y= vertices.at(triangleIndex.at(index + 2) * 3 + 1);
const double v3z= vertices.at(triangleIndex.at(index + 2) * 3 + 2);
resultVolume+= ((v2y - v1y) * (v3z - v1z) - (v2z - v1z) * (v3y - v1y)) * (v1x + v2x + v3x);
}
resultVolume= resultVolume / 6.0;
}
return resultVolume;
}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Set Functions // Set Functions
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -581,8 +635,11 @@ void GLC_Mesh::reverseNormals()
{ {
(*pNormalVector)[i]= - pNormalVector->at(i); (*pNormalVector)[i]= - pNormalVector->at(i);
} }
// Invalid the geometry if (vboIsUsed())
m_GeometryIsValid = false; {
m_MeshData.fillVbo(GLC_MeshData::GLC_Normal);
m_MeshData.useVBO(false, GLC_MeshData::GLC_Normal);
}
} }
// Copy index list in a vector for Vertex Array Use // Copy index list in a vector for Vertex Array Use
@ -592,14 +649,7 @@ void GLC_Mesh::finish()
m_MeshData.finishLod(); m_MeshData.finishLod();
if (GLC_State::vboUsed()) moveIndexToMeshDataLod();
{
finishVbo();
}
else
{
finishNonVbo();
}
//qDebug() << "Mesh mem size= " << memmorySize(); //qDebug() << "Mesh mem size= " << memmorySize();
} }
@ -692,6 +742,15 @@ void GLC_Mesh::releaseVboClientSide(bool update)
GLC_Geometry::releaseVboClientSide(update); GLC_Geometry::releaseVboClientSide(update);
} }
void GLC_Mesh::setVboUsage(bool usage)
{
if (!isEmpty())
{
GLC_Geometry::setVboUsage(usage);
m_MeshData.setVboUsage(usage);
}
}
// Load the mesh from binary data stream // Load the mesh from binary data stream
void GLC_Mesh::loadFromDataStream(QDataStream& stream, const MaterialHash& materialHash, const QHash<GLC_uint, GLC_uint>& materialIdMap) void GLC_Mesh::loadFromDataStream(QDataStream& stream, const MaterialHash& materialHash, const QHash<GLC_uint, GLC_uint>& materialIdMap)
{ {
@ -749,7 +808,6 @@ void GLC_Mesh::loadFromDataStream(QDataStream& stream, const MaterialHash& mater
stream >> m_NumberOfNormals; stream >> m_NumberOfNormals;
finishSerialized(); finishSerialized();
//qDebug() << "Mesh mem size= " << memmorySize();
} }
// Save the mesh to binary data stream // Save the mesh to binary data stream
@ -802,9 +860,10 @@ void GLC_Mesh::saveToDataStream(QDataStream& stream) const
// Virtual interface for OpenGL Geometry set up. // Virtual interface for OpenGL Geometry set up.
void GLC_Mesh::glDraw(const GLC_RenderProperties& renderProperties) void GLC_Mesh::glDraw(const GLC_RenderProperties& renderProperties)
{ {
Q_ASSERT(m_GeometryIsValid || !m_MeshData.normalVectorHandle()->isEmpty());
const bool vboIsUsed= GLC_State::vboUsed(); Q_ASSERT(m_GeometryIsValid || !m_MeshData.positionSizeIsSet());
const bool vboIsUsed= GLC_Geometry::vboIsUsed() && GLC_State::vboSupported();
if (m_IsSelected && (renderProperties.renderingMode() == glc::PrimitiveSelected) && !GLC_State::isInSelectionMode() if (m_IsSelected && (renderProperties.renderingMode() == glc::PrimitiveSelected) && !GLC_State::isInSelectionMode()
&& !renderProperties.setOfSelectedPrimitiveIdIsEmpty()) && !renderProperties.setOfSelectedPrimitiveIdIsEmpty())
@ -817,27 +876,20 @@ void GLC_Mesh::glDraw(const GLC_RenderProperties& renderProperties)
m_MeshData.createVBOs(); m_MeshData.createVBOs();
// Create VBO and IBO // Create VBO and IBO
if (!m_GeometryIsValid && !m_MeshData.positionVectorHandle()->isEmpty()) if (!m_GeometryIsValid && !m_MeshData.positionSizeIsSet())
{ {
fillVbosAndIbos(); fillVbosAndIbos();
} }
else if (!m_GeometryIsValid && !m_MeshData.normalVectorHandle()->isEmpty())
{
// Normals has been inversed update normal vbo
m_MeshData.useVBO(true, GLC_MeshData::GLC_Normal);
GLfloatVector* pNormalVector= m_MeshData.normalVectorHandle();
const GLsizei dataNbr= static_cast<GLsizei>(pNormalVector->size());
const GLsizeiptr dataSize= dataNbr * sizeof(GLfloat);
glBufferData(GL_ARRAY_BUFFER, dataSize, pNormalVector->data(), GL_STATIC_DRAW);
m_MeshData.normalVectorHandle()->clear();
}
// Activate mesh VBOs and IBO of the current LOD // Activate mesh VBOs and IBO of the current LOD
activateVboAndIbo(); activateVboAndIbo();
} }
else else
{ {
if (!m_GeometryIsValid)
{
m_MeshData.initPositionSize();
}
activateVertexArray(); activateVertexArray();
} }
@ -893,6 +945,9 @@ void GLC_Mesh::glDraw(const GLC_RenderProperties& renderProperties)
case glc::OverwriteTransparency: case glc::OverwriteTransparency:
OverwriteTransparencyRenderLoop(renderProperties, vboIsUsed); OverwriteTransparencyRenderLoop(renderProperties, vboIsUsed);
break; break;
case glc::OverwriteTransparencyAndMaterial:
OverwriteTransparencyAndMaterialRenderLoop(renderProperties, vboIsUsed);
break;
case glc::OverwritePrimitiveMaterial: case glc::OverwritePrimitiveMaterial:
if ((m_CurrentLod == 0) && !renderProperties.hashOfOverwritePrimitiveMaterialsIsEmpty()) if ((m_CurrentLod == 0) && !renderProperties.hashOfOverwritePrimitiveMaterialsIsEmpty())
primitiveRenderLoop(renderProperties, vboIsUsed); primitiveRenderLoop(renderProperties, vboIsUsed);
@ -907,11 +962,6 @@ void GLC_Mesh::glDraw(const GLC_RenderProperties& renderProperties)
// Restore client state // Restore client state
if (vboIsUsed)
{
m_MeshData.useIBO(false);
m_MeshData.useVBO(false, GLC_MeshData::GLC_Normal);
}
if (m_ColorPearVertex && !m_IsSelected && !GLC_State::isInSelectionMode()) if (m_ColorPearVertex && !m_IsSelected && !GLC_State::isInSelectionMode())
{ {
@ -923,12 +973,18 @@ void GLC_Mesh::glDraw(const GLC_RenderProperties& renderProperties)
glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY);
if (vboIsUsed)
{
QGLBuffer::release(QGLBuffer::IndexBuffer);
QGLBuffer::release(QGLBuffer::VertexBuffer);
}
// Draw mesh's wire if necessary // Draw mesh's wire if necessary
if ((renderProperties.renderingFlag() == glc::WireRenderFlag) && !m_WireData.isEmpty() && !GLC_Geometry::typeIsWire()) if ((renderProperties.renderingFlag() == glc::WireRenderFlag) && !m_WireData.isEmpty() && !GLC_Geometry::typeIsWire())
{ {
if (!GLC_State::isInSelectionMode()) if (!GLC_State::isInSelectionMode())
{ {
glDisable(GL_LIGHTING); GLC_Context::current()->glcEnableLighting(false);
// Set polyline colors // Set polyline colors
GLfloat color[4]= {static_cast<float>(m_WireColor.redF()), GLfloat color[4]= {static_cast<float>(m_WireColor.redF()),
static_cast<float>(m_WireColor.greenF()), static_cast<float>(m_WireColor.greenF()),
@ -937,7 +993,7 @@ void GLC_Mesh::glDraw(const GLC_RenderProperties& renderProperties)
glColor4fv(color); glColor4fv(color);
m_WireData.glDraw(renderProperties, GL_LINE_STRIP); m_WireData.glDraw(renderProperties, GL_LINE_STRIP);
glEnable(GL_LIGHTING); GLC_Context::current()->glcEnableLighting(true);
} }
else else
{ {
@ -1011,54 +1067,38 @@ GLC_uint GLC_Mesh::setCurrentMaterial(GLC_Material* pMaterial, int lod, double a
// Fill VBOs and IBOs // Fill VBOs and IBOs
void GLC_Mesh::fillVbosAndIbos() void GLC_Mesh::fillVbosAndIbos()
{ {
// Create VBO of vertices // Fill VBO of vertices
m_MeshData.fillVbo(GLC_MeshData::GLC_Vertex); m_MeshData.fillVbo(GLC_MeshData::GLC_Vertex);
// Create VBO of normals // Fill VBO of normals
m_MeshData.fillVbo(GLC_MeshData::GLC_Normal); m_MeshData.fillVbo(GLC_MeshData::GLC_Normal);
// Create VBO of texel if needed // Fill VBO of texel if needed
m_MeshData.fillVbo(GLC_MeshData::GLC_Texel); m_MeshData.fillVbo(GLC_MeshData::GLC_Texel);
// Create VBO of color if needed // Fill VBO of color if needed
m_MeshData.fillVbo(GLC_MeshData::GLC_Color); m_MeshData.fillVbo(GLC_MeshData::GLC_Color);
const int lodNumber= m_MeshData.lodCount(); // Fill a lod IBO
for (int i= 0; i < lodNumber; ++i) m_MeshData.fillLodIbo();
{
//Create LOD IBO
if (!m_MeshData.indexVectorHandle(i)->isEmpty())
{
QVector<GLuint>* pIndexVector= m_MeshData.indexVectorHandle(i);
m_MeshData.useIBO(true, i);
const GLsizei indexNbr= static_cast<GLsizei>(pIndexVector->size());
const GLsizeiptr indexSize = indexNbr * sizeof(GLuint);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexSize, pIndexVector->data(), GL_STATIC_DRAW);
}
}
// Remove client side data
m_MeshData.finishVbo();
} }
// set primitive group offset // set primitive group offset
void GLC_Mesh::finishSerialized() void GLC_Mesh::finishSerialized()
{ {
if (GLC_State::vboUsed()) PrimitiveGroupsHash::iterator iGroups= m_PrimitiveGroups.begin();
while (iGroups != m_PrimitiveGroups.constEnd())
{ {
PrimitiveGroupsHash::iterator iGroups= m_PrimitiveGroups.begin(); LodPrimitiveGroups::iterator iGroup= iGroups.value()->begin();
while (iGroups != m_PrimitiveGroups.constEnd()) while (iGroup != iGroups.value()->constEnd())
{ {
LodPrimitiveGroups::iterator iGroup= iGroups.value()->begin(); iGroup.value()->computeVboOffset();
while (iGroup != iGroups.value()->constEnd()) ++iGroup;
{
iGroup.value()->changeToVboMode();
++iGroup;
}
++iGroups;
} }
++iGroups;
} }
} }
/*
// Move Indexs from the primitive groups to the mesh Data LOD and Set IBOs offsets // Move Indexs from the primitive groups to the mesh Data LOD and Set IBOs offsets
void GLC_Mesh::finishVbo() void GLC_Mesh::finishVbo()
{ {
@ -1097,11 +1137,12 @@ void GLC_Mesh::finishVbo()
} }
} }
*/
// Move Indexs from the primitive groups to the mesh Data LOD and Set Index offsets // Move Indexs from the primitive groups to the mesh Data LOD and Set Index offsets
void GLC_Mesh::finishNonVbo() void GLC_Mesh::moveIndexToMeshDataLod()
{ {
//qDebug() << "GLC_Mesh::finishNonVbo()"; //qDebug() << "GLC_Mesh::moveIndexToMeshDataLod()";
PrimitiveGroupsHash::iterator iGroups= m_PrimitiveGroups.begin(); PrimitiveGroupsHash::iterator iGroups= m_PrimitiveGroups.begin();
while (iGroups != m_PrimitiveGroups.constEnd()) while (iGroups != m_PrimitiveGroups.constEnd())
{ {
@ -1130,6 +1171,7 @@ void GLC_Mesh::finishNonVbo()
(*m_MeshData.indexVectorHandle(currentLod))+= iGroup.value()->fansIndex().toVector(); (*m_MeshData.indexVectorHandle(currentLod))+= iGroup.value()->fansIndex().toVector();
} }
iGroup.value()->computeVboOffset();
iGroup.value()->finish(); iGroup.value()->finish();
++iGroup; ++iGroup;
} }
@ -1166,9 +1208,13 @@ void GLC_Mesh::normalRenderLoop(const GLC_RenderProperties& renderProperties, bo
{ {
if (vboIsUsed) if (vboIsUsed)
{
vboDrawPrimitivesOf(pCurrentGroup); vboDrawPrimitivesOf(pCurrentGroup);
}
else else
{
vertexArrayDrawPrimitivesOf(pCurrentGroup); vertexArrayDrawPrimitivesOf(pCurrentGroup);
}
} }
++iGroup; ++iGroup;
@ -1243,6 +1289,40 @@ void GLC_Mesh::OverwriteTransparencyRenderLoop(const GLC_RenderProperties& rende
} }
} }
void GLC_Mesh::OverwriteTransparencyAndMaterialRenderLoop(const GLC_RenderProperties& renderProperties, bool vboIsUsed)
{
// Get transparency value
const float alpha= renderProperties.overwriteTransparency();
Q_ASSERT(-1.0f != alpha);
// Get the overwrite material
GLC_Material* pOverwriteMaterial= renderProperties.overwriteMaterial();
Q_ASSERT(NULL != pOverwriteMaterial);
pOverwriteMaterial->glExecute(alpha);
if (m_IsSelected) GLC_SelectionMaterial::glExecute();
LodPrimitiveGroups::iterator iGroup= m_PrimitiveGroups.value(m_CurrentLod)->begin();
while (iGroup != m_PrimitiveGroups.value(m_CurrentLod)->constEnd())
{
GLC_PrimitiveGroup* pCurrentGroup= iGroup.value();
// Test if the current material is renderable
bool materialIsrenderable = (renderProperties.renderingFlag() == glc::TransparentRenderFlag);
// Choose the primitives to render
if (m_IsSelected || materialIsrenderable)
{
if (vboIsUsed)
vboDrawPrimitivesOf(pCurrentGroup);
else
vertexArrayDrawPrimitivesOf(pCurrentGroup);
}
++iGroup;
}
}
// The body selection render loop // The body selection render loop
void GLC_Mesh::bodySelectionRenderLoop(bool vboIsUsed) void GLC_Mesh::bodySelectionRenderLoop(bool vboIsUsed)
{ {
@ -1475,3 +1555,61 @@ void GLC_Mesh::copyBulkData(GLC_Mesh* pLodMesh, const QHash<GLuint, GLuint>& tag
tempFloatVector.clear(); tempFloatVector.clear();
} }
} }
IndexList GLC_Mesh::equivalentTrianglesIndexOfstripsIndex(int lodIndex, GLC_uint materialId)
{
IndexList trianglesIndex;
if (containsStrips(lodIndex, materialId))
{
const QList<QVector<GLuint> > stripsIndex= getStripsIndex(lodIndex, materialId);
const int stripCount= stripsIndex.count();
for (int i= 0; i < stripCount; ++i)
{
const QVector<GLuint> currentStripIndex= stripsIndex.at(i);
trianglesIndex.append(currentStripIndex.at(0));
trianglesIndex.append(currentStripIndex.at(1));
trianglesIndex.append(currentStripIndex.at(2));
const int stripSize= currentStripIndex.size();
for (int j= 3; j < stripSize; ++j)
{
if ((j % 2) != 0)
{
trianglesIndex.append(currentStripIndex.at(j));
trianglesIndex.append(currentStripIndex.at(j - 1));
trianglesIndex.append(currentStripIndex.at(j - 2));
}
else
{
trianglesIndex.append(currentStripIndex.at(j));
trianglesIndex.append(currentStripIndex.at(j - 2));
trianglesIndex.append(currentStripIndex.at(j - 1));
}
}
}
}
return trianglesIndex;
}
IndexList GLC_Mesh::equivalentTrianglesIndexOfFansIndex(int lodIndex, GLC_uint materialId)
{
IndexList trianglesIndex;
if (containsFans(lodIndex, materialId))
{
const QList<QVector<GLuint> > fanIndex= getFansIndex(lodIndex, materialId);
const int fanCount= fanIndex.count();
for (int i= 0; i < fanCount; ++i)
{
const QVector<GLuint> currentFanIndex= fanIndex.at(i);
const int size= currentFanIndex.size();
for (int j= 1; j < size - 1; ++j)
{
trianglesIndex.append(currentFanIndex.first());
trianglesIndex.append(currentFanIndex.at(j));
trianglesIndex.append(currentFanIndex.at(j + 1));
}
}
}
return trianglesIndex;
}

View File

@ -183,10 +183,12 @@ public:
//! Create a mesh from the given LOD index //! Create a mesh from the given LOD index
GLC_Mesh* createMeshFromGivenLod(int lodIndex); GLC_Mesh* createMeshFromGivenLod(int lodIndex);
//! Transform mesh vertice by the given matrix //! Transform mesh vertice by the given matrix
GLC_Mesh& transformVertice(const GLC_Matrix4x4& matrix); GLC_Mesh& transformVertice(const GLC_Matrix4x4& matrix);
//! Return the volume of this mesh
virtual double volume();
//@} //@}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
/*! \name Set Functions*/ /*! \name Set Functions*/
@ -264,6 +266,9 @@ public:
//! Release client VBO //! Release client VBO
virtual void releaseVboClientSide(bool update); virtual void releaseVboClientSide(bool update);
//! Set VBO usage
virtual void setVboUsage(bool usage);
//@} //@}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -309,10 +314,10 @@ private:
void finishSerialized(); void finishSerialized();
//! Move Indexs from the primitive groups to the mesh Data LOD and Set IBOs offsets //! Move Indexs from the primitive groups to the mesh Data LOD and Set IBOs offsets
void finishVbo(); //void finishVbo();
//! Move Indexs from the primitive groups to the mesh Data LOD and Set Index offsets //! Move Indexs from the primitive groups to the mesh Data LOD and Set Index offsets
void finishNonVbo(); void moveIndexToMeshDataLod();
//! Use VBO to Draw primitives from the specified GLC_PrimitiveGroup //! Use VBO to Draw primitives from the specified GLC_PrimitiveGroup
inline void vboDrawPrimitivesOf(GLC_PrimitiveGroup*); inline void vboDrawPrimitivesOf(GLC_PrimitiveGroup*);
@ -353,6 +358,9 @@ private:
//! The overwrite transparency render loop //! The overwrite transparency render loop
void OverwriteTransparencyRenderLoop(const GLC_RenderProperties&, bool); void OverwriteTransparencyRenderLoop(const GLC_RenderProperties&, bool);
//! The overwrite transparency and material render loop
void OverwriteTransparencyAndMaterialRenderLoop(const GLC_RenderProperties&, bool);
//! The body selection render loop //! The body selection render loop
void bodySelectionRenderLoop(bool); void bodySelectionRenderLoop(bool);
@ -371,6 +379,13 @@ private:
//! Copy Bulk data //! Copy Bulk data
void copyBulkData(GLC_Mesh* pLodMesh, const QHash<GLuint, GLuint>& tagetToSourceIndexMap, int maxIndex); void copyBulkData(GLC_Mesh* pLodMesh, const QHash<GLuint, GLuint>& tagetToSourceIndexMap, int maxIndex);
//! Return the equivalent triangles index of the strips index of given LOD and material ID
IndexList equivalentTrianglesIndexOfstripsIndex(int lodIndex, GLC_uint materialId);
//! Return the equivalent triangles index of the fan index of given LOD and material ID
IndexList equivalentTrianglesIndexOfFansIndex(int lodIndex, GLC_uint materialId);
//@} //@}

View File

@ -22,6 +22,7 @@
//! \file glc_meshdata.cpp Implementation for the GLC_MeshData class. //! \file glc_meshdata.cpp Implementation for the GLC_MeshData class.
#include "../glc_exception.h"
#include "glc_meshdata.h" #include "glc_meshdata.h"
#include "../glc_state.h" #include "../glc_state.h"
@ -30,36 +31,38 @@ quint32 GLC_MeshData::m_ChunkId= 0xA704;
// Default constructor // Default constructor
GLC_MeshData::GLC_MeshData() GLC_MeshData::GLC_MeshData()
: m_VboId(0) : m_VertexBuffer()
, m_Positions() , m_Positions()
, m_Normals() , m_Normals()
, m_Texels() , m_Texels()
, m_Colors() , m_Colors()
, m_NormalVboId(0) , m_NormalBuffer()
, m_TexelVboId(0) , m_TexelBuffer()
, m_ColorVboId(0) , m_ColorBuffer()
, m_LodList() , m_LodList()
, m_PositionSize(0) , m_PositionSize(-1)
, m_TexelsSize(0) , m_TexelsSize(-1)
, m_ColorSize(0) , m_ColorSize(-1)
, m_UseVbo(false)
{ {
} }
// Copy constructor // Copy constructor
GLC_MeshData::GLC_MeshData(const GLC_MeshData& meshData) GLC_MeshData::GLC_MeshData(const GLC_MeshData& meshData)
: m_VboId(0) : m_VertexBuffer()
, m_Positions(meshData.positionVector()) , m_Positions(meshData.positionVector())
, m_Normals(meshData.normalVector()) , m_Normals(meshData.normalVector())
, m_Texels(meshData.texelVector()) , m_Texels(meshData.texelVector())
, m_Colors(meshData.colorVector()) , m_Colors(meshData.colorVector())
, m_NormalVboId(0) , m_NormalBuffer()
, m_TexelVboId(0) , m_TexelBuffer()
, m_ColorVboId(0) , m_ColorBuffer()
, m_LodList() , m_LodList()
, m_PositionSize(meshData.m_PositionSize) , m_PositionSize(meshData.m_PositionSize)
, m_TexelsSize(meshData.m_TexelsSize) , m_TexelsSize(meshData.m_TexelsSize)
, m_ColorSize(meshData.m_ColorSize) , m_ColorSize(meshData.m_ColorSize)
, m_UseVbo(meshData.m_UseVbo)
{ {
// Copy meshData LOD list // Copy meshData LOD list
const int size= meshData.m_LodList.size(); const int size= meshData.m_LodList.size();
@ -85,6 +88,7 @@ GLC_MeshData& GLC_MeshData::operator=(const GLC_MeshData& meshData)
m_PositionSize= meshData.m_PositionSize; m_PositionSize= meshData.m_PositionSize;
m_TexelsSize= meshData.m_TexelsSize; m_TexelsSize= meshData.m_TexelsSize;
m_ColorSize= meshData.m_ColorSize; m_ColorSize= meshData.m_ColorSize;
m_UseVbo= meshData.m_UseVbo;
// Copy meshData LOD list // Copy meshData LOD list
const int size= meshData.m_LodList.size(); const int size= meshData.m_LodList.size();
@ -112,18 +116,22 @@ quint32 GLC_MeshData::chunckID()
// Return the Position Vector // Return the Position Vector
GLfloatVector GLC_MeshData::positionVector() const GLfloatVector GLC_MeshData::positionVector() const
{ {
if (0 != m_VboId) if (m_VertexBuffer.isCreated())
{ {
// VBO created get data from VBO // VBO created get data from VBO
const int sizeOfVbo= m_PositionSize; const int sizeOfVbo= m_PositionSize;
const GLsizeiptr dataSize= sizeOfVbo * sizeof(float); const GLsizeiptr dataSize= sizeOfVbo * sizeof(float);
GLfloatVector positionVector(sizeOfVbo); GLfloatVector positionVector(sizeOfVbo);
glBindBuffer(GL_ARRAY_BUFFER, m_VboId); if (!const_cast<QGLBuffer&>(m_VertexBuffer).bind())
GLvoid* pVbo = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_ONLY); {
GLC_Exception exception("GLC_MeshData::positionVector() Failed to bind vertex buffer");
throw(exception);
}
GLvoid* pVbo = const_cast<QGLBuffer&>(m_VertexBuffer).map(QGLBuffer::ReadOnly);
memcpy(positionVector.data(), pVbo, dataSize); memcpy(positionVector.data(), pVbo, dataSize);
glUnmapBuffer(GL_ARRAY_BUFFER); const_cast<QGLBuffer&>(m_VertexBuffer).unmap();
glBindBuffer(GL_ARRAY_BUFFER, 0); const_cast<QGLBuffer&>(m_VertexBuffer).release();
return positionVector; return positionVector;
} }
else else
@ -135,18 +143,18 @@ GLfloatVector GLC_MeshData::positionVector() const
// Return the normal Vector // Return the normal Vector
GLfloatVector GLC_MeshData::normalVector() const GLfloatVector GLC_MeshData::normalVector() const
{ {
if (0 != m_NormalVboId) if (m_NormalBuffer.isCreated())
{ {
// VBO created get data from VBO // VBO created get data from VBO
const int sizeOfVbo= m_PositionSize; const int sizeOfVbo= m_PositionSize;
const GLsizeiptr dataSize= sizeOfVbo * sizeof(GLfloat); const GLsizeiptr dataSize= sizeOfVbo * sizeof(GLfloat);
GLfloatVector normalVector(sizeOfVbo); GLfloatVector normalVector(sizeOfVbo);
glBindBuffer(GL_ARRAY_BUFFER, m_NormalVboId); const_cast<QGLBuffer&>(m_NormalBuffer).bind();
GLvoid* pVbo = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_ONLY); GLvoid* pVbo = const_cast<QGLBuffer&>(m_NormalBuffer).map(QGLBuffer::ReadOnly);
memcpy(normalVector.data(), pVbo, dataSize); memcpy(normalVector.data(), pVbo, dataSize);
glUnmapBuffer(GL_ARRAY_BUFFER); const_cast<QGLBuffer&>(m_NormalBuffer).unmap();
glBindBuffer(GL_ARRAY_BUFFER, 0); const_cast<QGLBuffer&>(m_NormalBuffer).release();
return normalVector; return normalVector;
} }
else else
@ -158,18 +166,18 @@ GLfloatVector GLC_MeshData::normalVector() const
// Return the texel Vector // Return the texel Vector
GLfloatVector GLC_MeshData::texelVector() const GLfloatVector GLC_MeshData::texelVector() const
{ {
if (0 != m_TexelVboId) if (m_TexelBuffer.isCreated())
{ {
// VBO created get data from VBO // VBO created get data from VBO
const int sizeOfVbo= m_TexelsSize; const int sizeOfVbo= m_TexelsSize;
const GLsizeiptr dataSize= sizeOfVbo * sizeof(GLfloat); const GLsizeiptr dataSize= sizeOfVbo * sizeof(GLfloat);
GLfloatVector texelVector(sizeOfVbo); GLfloatVector texelVector(sizeOfVbo);
glBindBuffer(GL_ARRAY_BUFFER, m_TexelVboId); const_cast<QGLBuffer&>(m_TexelBuffer).bind();
GLvoid* pVbo = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_ONLY); GLvoid* pVbo = const_cast<QGLBuffer&>(m_TexelBuffer).map(QGLBuffer::ReadOnly);
memcpy(texelVector.data(), pVbo, dataSize); memcpy(texelVector.data(), pVbo, dataSize);
glUnmapBuffer(GL_ARRAY_BUFFER); const_cast<QGLBuffer&>(m_TexelBuffer).unmap();
glBindBuffer(GL_ARRAY_BUFFER, 0); const_cast<QGLBuffer&>(m_TexelBuffer).release();
return texelVector; return texelVector;
} }
else else
@ -181,18 +189,18 @@ GLfloatVector GLC_MeshData::texelVector() const
// Return the color Vector // Return the color Vector
GLfloatVector GLC_MeshData::colorVector() const GLfloatVector GLC_MeshData::colorVector() const
{ {
if (0 != m_ColorVboId) if (m_ColorBuffer.isCreated())
{ {
// VBO created get data from VBO // VBO created get data from VBO
const int sizeOfVbo= m_ColorSize; const int sizeOfVbo= m_ColorSize;
const GLsizeiptr dataSize= sizeOfVbo * sizeof(GLfloat); const GLsizeiptr dataSize= sizeOfVbo * sizeof(GLfloat);
GLfloatVector normalVector(sizeOfVbo); GLfloatVector normalVector(sizeOfVbo);
glBindBuffer(GL_ARRAY_BUFFER, m_ColorVboId); const_cast<QGLBuffer&>(m_ColorBuffer).bind();
GLvoid* pVbo = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_ONLY); GLvoid* pVbo = const_cast<QGLBuffer&>(m_ColorBuffer).map(QGLBuffer::ReadOnly);
memcpy(normalVector.data(), pVbo, dataSize); memcpy(normalVector.data(), pVbo, dataSize);
glUnmapBuffer(GL_ARRAY_BUFFER); const_cast<QGLBuffer&>(m_ColorBuffer).unmap();
glBindBuffer(GL_ARRAY_BUFFER, 0); const_cast<QGLBuffer&>(m_ColorBuffer).release();
return normalVector; return normalVector;
} }
else else
@ -205,25 +213,6 @@ GLfloatVector GLC_MeshData::colorVector() const
// Set Functions // Set Functions
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// The mesh wich use the data is finished
void GLC_MeshData::finishVbo()
{
m_PositionSize= m_Positions.size();
m_Positions.clear();
m_Normals.clear();
m_TexelsSize= m_Texels.size();
m_Texels.clear();
m_ColorSize= m_Colors.size();
m_Colors.clear();
// Finish the LOD
const int size= m_LodList.size();
for (int i= 0; i < size; ++i)
{
m_LodList[i]->finishVbo();
}
}
// If the there is more than 2 LOD Swap the first and last // If the there is more than 2 LOD Swap the first and last
void GLC_MeshData::finishLod() void GLC_MeshData::finishLod()
{ {
@ -244,35 +233,31 @@ void GLC_MeshData::clear()
m_Normals.clear(); m_Normals.clear();
m_Texels.clear(); m_Texels.clear();
m_Colors.clear(); m_Colors.clear();
m_PositionSize= 0; m_PositionSize= -1;
m_TexelsSize= 0; m_TexelsSize= -1;
m_ColorSize= 0; m_ColorSize= -1;
// Delete Main Vbo ID // Delete Main Vbo ID
if (0 != m_VboId) if (m_VertexBuffer.isCreated())
{ {
glDeleteBuffers(1, &m_VboId); m_VertexBuffer.destroy();
m_VboId= 0;
} }
// Delete Normal VBO // Delete Normal VBO
if (0 != m_NormalVboId) if (m_NormalBuffer.isCreated())
{ {
glDeleteBuffers(1, &m_NormalVboId); m_NormalBuffer.destroy();
m_NormalVboId= 0;
} }
// Delete Texel VBO // Delete Texel VBO
if (0 != m_TexelVboId) if (m_TexelBuffer.isCreated())
{ {
glDeleteBuffers(1, &m_TexelVboId); m_TexelBuffer.destroy();
m_TexelVboId= 0;
} }
// Delete color index // Delete color index
if (0 != m_ColorVboId) if (m_ColorBuffer.isCreated())
{ {
glDeleteBuffers(1, &m_ColorVboId); m_ColorBuffer.destroy();
m_ColorVboId= 0;
} }
const int size= m_LodList.size(); const int size= m_LodList.size();
@ -286,16 +271,16 @@ void GLC_MeshData::clear()
void GLC_MeshData::copyVboToClientSide() void GLC_MeshData::copyVboToClientSide()
{ {
if ((0 != m_VboId) && m_Positions.isEmpty()) if (m_VertexBuffer.isCreated() && m_Positions.isEmpty())
{ {
Q_ASSERT(0 != m_NormalVboId); Q_ASSERT(m_NormalBuffer.isCreated());
m_Positions= positionVector(); m_Positions= positionVector();
m_Normals= normalVector(); m_Normals= normalVector();
if (0 != m_TexelVboId) if (m_TexelBuffer.isCreated())
{ {
m_Texels= texelVector(); m_Texels= texelVector();
} }
if (0 != m_ColorVboId) if (m_ColorBuffer.isCreated())
{ {
m_Colors= colorVector(); m_Colors= colorVector();
} }
@ -304,7 +289,7 @@ void GLC_MeshData::copyVboToClientSide()
void GLC_MeshData::releaseVboClientSide(bool update) void GLC_MeshData::releaseVboClientSide(bool update)
{ {
if ((0 != m_VboId) && !m_Positions.isEmpty()) if (m_VertexBuffer.isCreated() && !m_Positions.isEmpty())
{ {
if (update) if (update)
{ {
@ -324,28 +309,82 @@ void GLC_MeshData::releaseVboClientSide(bool update)
} }
} }
void GLC_MeshData::setVboUsage(bool usage)
{
if (usage && (m_PositionSize != -1) && (!m_Positions.isEmpty()) && (!m_VertexBuffer.isCreated()))
{
createVBOs();
fillVbo(GLC_MeshData::GLC_Vertex);
fillVbo(GLC_MeshData::GLC_Normal);
fillVbo(GLC_MeshData::GLC_Texel);
fillVbo(GLC_MeshData::GLC_Color);
useVBO(false, GLC_MeshData::GLC_Color);
const int lodCount= m_LodList.count();
for (int i= 0; i < lodCount; ++i)
{
m_LodList.at(i)->setIboUsage(usage);
}
}
else if (!usage && m_VertexBuffer.isCreated())
{
m_Positions= positionVector();
m_PositionSize= m_Positions.size();
m_VertexBuffer.destroy();
m_Normals= normalVector();
m_NormalBuffer.destroy();
if (m_TexelBuffer.isCreated())
{
m_Texels= texelVector();
m_TexelsSize= m_Texels.size();
m_TexelBuffer.destroy();
}
if (m_ColorBuffer.isCreated())
{
m_Colors= colorVector();
m_ColorSize= m_Colors.size();
m_ColorBuffer.destroy();
}
const int lodCount= m_LodList.count();
for (int i= 0; i < lodCount; ++i)
{
m_LodList.at(i)->setIboUsage(usage);
}
}
m_UseVbo= usage;
}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// OpenGL Functions // OpenGL Functions
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Vbo creation // Vbo creation
void GLC_MeshData::createVBOs() void GLC_MeshData::createVBOs()
{ {
// Create position VBO // Create position VBO
if (0 == m_VboId) if (!m_VertexBuffer.isCreated())
{ {
glGenBuffers(1, &m_VboId); Q_ASSERT((NULL != QGLContext::currentContext()) && QGLContext::currentContext()->isValid());
glGenBuffers(1, &m_NormalVboId);
m_VertexBuffer.create();
m_NormalBuffer.create();
// Create Texel VBO // Create Texel VBO
if (0 == m_TexelVboId && !m_Texels.isEmpty()) if (!m_TexelBuffer.isCreated() && !m_Texels.isEmpty())
{ {
glGenBuffers(1, &m_TexelVboId); m_TexelBuffer.create();
} }
// Create Color VBO // Create Color VBO
if (0 == m_ColorVboId && !m_Colors.isEmpty()) if (!m_ColorBuffer.isCreated() && !m_Colors.isEmpty())
{ {
glGenBuffers(1, &m_ColorVboId); m_ColorBuffer.create();
} }
const int size= m_LodList.size(); const int size= m_LodList.size();
@ -357,7 +396,7 @@ void GLC_MeshData::createVBOs()
} }
// Ibo Usage // Ibo Usage
bool GLC_MeshData::useVBO(bool use, GLC_MeshData::VboType type) const bool GLC_MeshData::useVBO(bool use, GLC_MeshData::VboType type)
{ {
bool result= true; bool result= true;
if (use) if (use)
@ -365,19 +404,35 @@ bool GLC_MeshData::useVBO(bool use, GLC_MeshData::VboType type) const
// Chose the right VBO // Chose the right VBO
if (type == GLC_MeshData::GLC_Vertex) if (type == GLC_MeshData::GLC_Vertex)
{ {
glBindBuffer(GL_ARRAY_BUFFER, m_VboId); if (!m_VertexBuffer.bind())
{
GLC_Exception exception("GLC_MeshData::useVBO Failed to bind vertex buffer");
throw(exception);
}
} }
else if (type == GLC_MeshData::GLC_Normal) else if (type == GLC_MeshData::GLC_Normal)
{ {
glBindBuffer(GL_ARRAY_BUFFER, m_NormalVboId); if (!m_NormalBuffer.bind())
{
GLC_Exception exception("GLC_MeshData::useVBO Failed to bind normal buffer");
throw(exception);
}
} }
else if ((type == GLC_MeshData::GLC_Texel) && (0 != m_TexelVboId)) else if ((type == GLC_MeshData::GLC_Texel) && m_TexelBuffer.isCreated())
{ {
glBindBuffer(GL_ARRAY_BUFFER, m_TexelVboId); if (!m_TexelBuffer.bind())
{
GLC_Exception exception("GLC_MeshData::useVBO Failed to bind texel buffer");
throw(exception);
}
} }
else if ((type == GLC_MeshData::GLC_Color) && (0 != m_ColorVboId)) else if ((type == GLC_MeshData::GLC_Color) && m_ColorBuffer.isCreated())
{ {
glBindBuffer(GL_ARRAY_BUFFER, m_ColorVboId); if (!m_ColorBuffer.bind())
{
GLC_Exception exception("GLC_MeshData::useVBO Failed to bind color buffer");
throw(exception);
}
} }
else result= false; else result= false;
@ -385,7 +440,7 @@ bool GLC_MeshData::useVBO(bool use, GLC_MeshData::VboType type) const
else else
{ {
// Unbind VBO // Unbind VBO
glBindBuffer(GL_ARRAY_BUFFER, 0); QGLBuffer::release(QGLBuffer::VertexBuffer);
} }
return result; return result;
} }
@ -398,28 +453,48 @@ void GLC_MeshData::fillVbo(GLC_MeshData::VboType type)
useVBO(true, type); useVBO(true, type);
const GLsizei dataNbr= static_cast<GLsizei>(m_Positions.size()); const GLsizei dataNbr= static_cast<GLsizei>(m_Positions.size());
const GLsizeiptr dataSize= dataNbr * sizeof(GLfloat); const GLsizeiptr dataSize= dataNbr * sizeof(GLfloat);
glBufferData(GL_ARRAY_BUFFER, dataSize, m_Positions.data(), GL_STATIC_DRAW); m_VertexBuffer.allocate(m_Positions.data(), dataSize);
m_PositionSize= m_Positions.size();
m_Positions.clear();
} }
else if (type == GLC_MeshData::GLC_Normal) else if (type == GLC_MeshData::GLC_Normal)
{ {
useVBO(true, type); useVBO(true, type);
const GLsizei dataNbr= static_cast<GLsizei>(m_Normals.size()); const GLsizei dataNbr= static_cast<GLsizei>(m_Normals.size());
const GLsizeiptr dataSize= dataNbr * sizeof(GLfloat); const GLsizeiptr dataSize= dataNbr * sizeof(GLfloat);
glBufferData(GL_ARRAY_BUFFER, dataSize, m_Normals.data(), GL_STATIC_DRAW); m_NormalBuffer.allocate(m_Normals.data(), dataSize);
m_Normals.clear();
} }
else if ((type == GLC_MeshData::GLC_Texel) && (0 != m_TexelVboId)) else if ((type == GLC_MeshData::GLC_Texel) && m_TexelBuffer.isCreated())
{ {
useVBO(true, type); useVBO(true, type);
const GLsizei dataNbr= static_cast<GLsizei>(m_Texels.size()); const GLsizei dataNbr= static_cast<GLsizei>(m_Texels.size());
const GLsizeiptr dataSize= dataNbr * sizeof(GLfloat); const GLsizeiptr dataSize= dataNbr * sizeof(GLfloat);
glBufferData(GL_ARRAY_BUFFER, dataSize, m_Texels.data(), GL_STATIC_DRAW); m_TexelBuffer.allocate(m_Texels.data(), dataSize);
m_TexelsSize= m_Texels.size();
m_Texels.clear();
} }
else if ((type == GLC_MeshData::GLC_Color) && (0 != m_ColorVboId)) else if ((type == GLC_MeshData::GLC_Color) && m_ColorBuffer.isCreated())
{ {
useVBO(true, type); useVBO(true, type);
const GLsizei dataNbr= static_cast<GLsizei>(m_Colors.size()); const GLsizei dataNbr= static_cast<GLsizei>(m_Colors.size());
const GLsizeiptr dataSize= dataNbr * sizeof(GLfloat); const GLsizeiptr dataSize= dataNbr * sizeof(GLfloat);
glBufferData(GL_ARRAY_BUFFER, dataSize, m_Colors.data(), GL_STATIC_DRAW); m_ColorBuffer.allocate(m_Colors.data(), dataSize);
m_ColorSize= m_Colors.size();
m_Colors.clear();
}
}
void GLC_MeshData::fillLodIbo()
{
const int lodCount= m_LodList.count();
for (int i= 0; i < lodCount; ++i)
{
m_LodList.at(i)->fillIbo();
} }
} }
// Non Member methods // Non Member methods

View File

@ -26,6 +26,7 @@
#define GLC_MESHDATA_H_ #define GLC_MESHDATA_H_
#include <QVector> #include <QVector>
#include <QGLBuffer>
#include "glc_lod.h" #include "glc_lod.h"
#include "../glc_global.h" #include "../glc_global.h"
@ -140,7 +141,7 @@ public:
//! Return true if the mesh data doesn't contains vertice //! Return true if the mesh data doesn't contains vertice
inline bool isEmpty() const inline bool isEmpty() const
{return (0 == m_PositionSize) && (0 == m_Positions.size());} {return (1 > m_PositionSize) && (0 == m_Positions.size());}
//! Return the number of triangle from the given lod index //! Return the number of triangle from the given lod index
inline unsigned int trianglesCount(int lod) const inline unsigned int trianglesCount(int lod) const
@ -149,6 +150,10 @@ public:
return m_LodList.at(lod)->trianglesCount(); return m_LodList.at(lod)->trianglesCount();
} }
//! Return true if the position size is set
inline bool positionSizeIsSet() const
{return m_PositionSize != -1;}
//@} //@}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -160,9 +165,6 @@ public:
inline void appendLod(double accuracy= 0.0) inline void appendLod(double accuracy= 0.0)
{m_LodList.append(new GLC_Lod(accuracy));} {m_LodList.append(new GLC_Lod(accuracy));}
//! The mesh wich use the data is finished and VBO is used
void finishVbo();
//! If the there is more than 2 LOD Swap the first and last //! If the there is more than 2 LOD Swap the first and last
void finishLod(); void finishLod();
@ -183,6 +185,13 @@ public:
m_LodList.at(lod)->trianglesAdded(number); m_LodList.at(lod)->trianglesAdded(number);
} }
//! Set VBO usage
void setVboUsage(bool usage);
//! Init the position size
inline void initPositionSize()
{m_PositionSize= m_Positions.size();}
//@} //@}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -194,15 +203,18 @@ public:
void createVBOs(); void createVBOs();
//! Ibo Usage //! Ibo Usage
bool useVBO(bool, GLC_MeshData::VboType) const; bool useVBO(bool, GLC_MeshData::VboType);
//! Ibo Usage //! Ibo Usage
inline void useIBO(bool use, const int currentLod= 0) inline void useIBO(bool use, const int currentLod= 0)
{ {
if (use) m_LodList.at(currentLod)->useIBO(); if (use) m_LodList.at(currentLod)->useIBO();
else glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); else QGLBuffer::release(QGLBuffer::IndexBuffer);
} }
//! Fill all LOD IBO
void fillLodIbo();
//! Fill the VBO of the given type //! Fill the VBO of the given type
void fillVbo(GLC_MeshData::VboType vboType); void fillVbo(GLC_MeshData::VboType vboType);
@ -213,8 +225,8 @@ public:
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
private: private:
//! Main VBO ID //! The vertex Buffer
GLuint m_VboId; QGLBuffer m_VertexBuffer;
//! Vertex Position Vector //! Vertex Position Vector
GLfloatVector m_Positions; GLfloatVector m_Positions;
@ -228,14 +240,14 @@ private:
//! Color index //! Color index
GLfloatVector m_Colors; GLfloatVector m_Colors;
//! Normals VBO ID //! Normals Buffer
GLuint m_NormalVboId; QGLBuffer m_NormalBuffer;
//! Texture VBO ID //! Texture Buffer
GLuint m_TexelVboId; QGLBuffer m_TexelBuffer;
//! Color VBO ID //! Color Buffer
GLuint m_ColorVboId; QGLBuffer m_ColorBuffer;
//! The list of LOD //! The list of LOD
QList<GLC_Lod*> m_LodList; QList<GLC_Lod*> m_LodList;
@ -249,6 +261,9 @@ private:
//! The size of Color VBO //! The size of Color VBO
int m_ColorSize; int m_ColorSize;
//! Use VBO
bool m_UseVbo;
//! Class chunk id //! Class chunk id
static quint32 m_ChunkId; static quint32 m_ChunkId;
}; };

View File

@ -32,18 +32,27 @@ using namespace glc;
GLC_Point::GLC_Point(const GLC_Point3d &setCoord) GLC_Point::GLC_Point(const GLC_Point3d &setCoord)
:GLC_Geometry("Point", true) :GLC_PointCloud()
, m_Coordinate(setCoord) , m_Coordinate(setCoord)
, m_Size(1.0f) , m_Size(1.0f)
{ {
setCoordinate(m_Coordinate);
} }
//! Construct an GLC_Point
GLC_Point::GLC_Point(double x, double y, double z) GLC_Point::GLC_Point(double x, double y, double z)
:GLC_Geometry("Point", true) :GLC_PointCloud()
, m_Coordinate(x, y, z) , m_Coordinate(x, y, z)
, m_Size(1.0f) , m_Size(1.0f)
{ {
setCoordinate(m_Coordinate);
}
GLC_Point::GLC_Point(const GLC_Point& point)
:GLC_PointCloud(point)
, m_Coordinate(point.m_Coordinate)
, m_Size(point.m_Size)
{
} }
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -56,26 +65,6 @@ GLC_Point3d GLC_Point::coordinate(void) const
return m_Coordinate; return m_Coordinate;
} }
// return the point bounding box
const GLC_BoundingBox& GLC_Point::boundingBox(void)
{
if (NULL == m_pBoundingBox)
{
m_pBoundingBox= new GLC_BoundingBox();
const double delta= 1e-2;
GLC_Point3d lower(m_Coordinate.x() - delta,
m_Coordinate.y() - delta,
m_Coordinate.z() - delta);
GLC_Point3d upper(m_Coordinate.x() + delta,
m_Coordinate.y() + delta,
m_Coordinate.z() + delta);
m_pBoundingBox->combine(lower);
m_pBoundingBox->combine(upper);
}
return *m_pBoundingBox;
}
// Return a copy of the current geometry // Return a copy of the current geometry
GLC_Geometry* GLC_Point::clone() const GLC_Geometry* GLC_Point::clone() const
{ {
@ -90,32 +79,26 @@ GLC_Geometry* GLC_Point::clone() const
void GLC_Point::setCoordinate(const GLC_Point3d &point) void GLC_Point::setCoordinate(const GLC_Point3d &point)
{ {
m_Coordinate= point; m_Coordinate= point;
GLC_PointCloud::clear();
QList<GLC_Point3d> points;
points.append(m_Coordinate);
GLC_PointCloud::addPoint(points);
} }
// Set Point coordinate by 3 double // Set Point coordinate by 3 double
void GLC_Point::setCoordinate(double x, double y, double z) void GLC_Point::setCoordinate(double x, double y, double z)
{ {
m_Coordinate.setVect(x, y, z); setCoordinate(GLC_Point3d(x, y, z));
} }
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// OpenGL Functions // OpenGL Functions
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
void GLC_Point::glDraw(const GLC_RenderProperties&) void GLC_Point::glDraw(const GLC_RenderProperties& renderProperties)
{ {
glPointSize(m_Size); glPointSize(m_Size);
// Point Display // Point Display
glBegin(GL_POINTS); GLC_PointCloud::glDraw(renderProperties);
glVertex3dv(m_Coordinate.data());
glEnd();
glPointSize(1.0f);
// OpenGL error handler
GLenum error= glGetError();
if (error != GL_NO_ERROR)
{
GLC_OpenGlException OpenGlException("GLC_Point::GlDraw ", error);
throw(OpenGlException);
}
} }

View File

@ -25,7 +25,7 @@
#ifndef GLC_POINT_H_ #ifndef GLC_POINT_H_
#define GLC_POINT_H_ #define GLC_POINT_H_
#include "glc_geometry.h" #include "glc_pointcloud.h"
#include "../glc_config.h" #include "../glc_config.h"
@ -36,7 +36,7 @@
/*! An GLC_Point is just a simple 3D Point*/ /*! An GLC_Point is just a simple 3D Point*/
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
class GLC_LIB_EXPORT GLC_Point : public GLC_Geometry class GLC_LIB_EXPORT GLC_Point : public GLC_PointCloud
{ {
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
/*! @name Constructor / Destructor */ /*! @name Constructor / Destructor */
@ -49,6 +49,9 @@ public:
//! Construct an GLC_Point //! Construct an GLC_Point
GLC_Point(double, double, double); GLC_Point(double, double, double);
//! Copy constructor
GLC_Point(const GLC_Point& point);
//@} //@}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -60,9 +63,6 @@ public:
//! Return a GLC_Point3d of coordinate //! Return a GLC_Point3d of coordinate
GLC_Point3d coordinate(void) const; GLC_Point3d coordinate(void) const;
//! Return the point bounding box
virtual const GLC_BoundingBox& boundingBox(void);
//! Return a copy of the geometry //! Return a copy of the geometry
virtual GLC_Geometry* clone() const; virtual GLC_Geometry* clone() const;

View File

@ -96,6 +96,23 @@ GLC_uint GLC_PointCloud::addPoint(const QList<GLC_Point3df>& pointsList)
return GLC_Geometry::m_WireData.addVerticeGroup(data); return GLC_Geometry::m_WireData.addVerticeGroup(data);
} }
void GLC_PointCloud::addColors(const QList<QColor>& colors)
{
const int colorCount= colors.count();
const int size= colorCount * 4;
GLfloatVector data(size);
for (int i= 0; i < colorCount; ++i)
{
QColor color= colors.at(i);
data[i * 4]= static_cast<GLfloat>(color.redF());
data[i * 4 + 1]= static_cast<GLfloat>(color.greenF());
data[i * 4 + 2]= static_cast<GLfloat>(color.blueF());
data[i * 4 + 3]= static_cast<GLfloat>(color.alphaF());
}
GLC_Geometry::m_WireData.addColors(data);
}
GLC_PointCloud& GLC_PointCloud::operator=(const GLC_PointCloud& pointCloud) GLC_PointCloud& GLC_PointCloud::operator=(const GLC_PointCloud& pointCloud)
{ {
if (this != &pointCloud) if (this != &pointCloud)

View File

@ -86,6 +86,13 @@ public:
//! Add the given list of points to this cloud and returns its id if id are managed //! Add the given list of points to this cloud and returns its id if id are managed
GLC_uint addPoint(const QList<GLC_Point3df>& pointsList); GLC_uint addPoint(const QList<GLC_Point3df>& pointsList);
//! Add Colors
inline void addColors(const GLfloatVector& colors)
{GLC_Geometry::m_WireData.addColors(colors);}
//! Add Colors
void addColors(const QList<QColor>& colors);
//! Set this point cloud from the given point cloud and return a reference of this point cloud //! Set this point cloud from the given point cloud and return a reference of this point cloud
GLC_PointCloud& operator=(const GLC_PointCloud& pointcloud); GLC_PointCloud& operator=(const GLC_PointCloud& pointcloud);
@ -99,7 +106,7 @@ public:
/*! \name OpenGL Functions*/ /*! \name OpenGL Functions*/
//@{ //@{
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
private: protected:
//! Virtual interface for OpenGL Geometry set up. //! Virtual interface for OpenGL Geometry set up.
/*! This Virtual function is implemented here.\n /*! This Virtual function is implemented here.\n

View File

@ -27,13 +27,14 @@
#include "../glc_state.h" #include "../glc_state.h"
#include "../glc_ext.h" #include "../glc_ext.h"
#include "../shading/glc_selectionmaterial.h" #include "../shading/glc_selectionmaterial.h"
#include "../glc_context.h"
// The maximum point size // The maximum point size
float GLC_PointSprite::m_MaxSize= -1.0f; float GLC_PointSprite::m_MaxSize= -1.0f;
// Default constructor // Default constructor
GLC_PointSprite::GLC_PointSprite(float size, GLC_Material* pMaterial) GLC_PointSprite::GLC_PointSprite(float size, GLC_Material* pMaterial)
:GLC_Geometry("PointSprite", false) :GLC_PointCloud()
, m_Size(size) , m_Size(size)
, m_DistanceAttenuation(3) , m_DistanceAttenuation(3)
, m_FadeThresoldSize(60.0f) , m_FadeThresoldSize(60.0f)
@ -46,6 +47,19 @@ GLC_PointSprite::GLC_PointSprite(float size, GLC_Material* pMaterial)
m_DistanceAttenuation[0]= 1.0f; m_DistanceAttenuation[0]= 1.0f;
m_DistanceAttenuation[1]= 0.0f; m_DistanceAttenuation[1]= 0.0f;
m_DistanceAttenuation[2]= 0.0f; m_DistanceAttenuation[2]= 0.0f;
QList<GLC_Point3d> points;
points.append(GLC_Point3d(0.0, 0.0, 0.0));
GLC_PointCloud::addPoint(points);
}
GLC_PointSprite::GLC_PointSprite(const GLC_PointSprite& point)
: GLC_PointCloud(point)
, m_Size(point.m_Size)
, m_DistanceAttenuation(point.m_DistanceAttenuation)
, m_FadeThresoldSize(point.m_FadeThresoldSize)
{
} }
GLC_PointSprite::~GLC_PointSprite() GLC_PointSprite::~GLC_PointSprite()
@ -53,26 +67,6 @@ GLC_PointSprite::~GLC_PointSprite()
} }
// return the point bounding box
const GLC_BoundingBox& GLC_PointSprite::boundingBox(void)
{
if (NULL == m_pBoundingBox)
{
m_pBoundingBox= new GLC_BoundingBox();
const double epsilon= 1e-2;
GLC_Point3d lower( - epsilon,
- epsilon,
- epsilon);
GLC_Point3d upper( epsilon,
epsilon,
epsilon);
m_pBoundingBox->combine(lower);
m_pBoundingBox->combine(upper);
}
return *m_pBoundingBox;
}
// Return a copy of the current geometry // Return a copy of the current geometry
GLC_Geometry* GLC_PointSprite::clone() const GLC_Geometry* GLC_PointSprite::clone() const
{ {
@ -116,6 +110,7 @@ void GLC_PointSprite::render(const GLC_RenderProperties& renderProperties)
glEnable(GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_LIGHTING); glDisable(GL_LIGHTING);
//GLC_Context::current()->glcEnableLighting(false);
if(m_MaterialHash.size() == 1) if(m_MaterialHash.size() == 1)
{ {
@ -143,6 +138,7 @@ void GLC_PointSprite::render(const GLC_RenderProperties& renderProperties)
glDisable(GL_BLEND); glDisable(GL_BLEND);
glDisable(GL_TEXTURE_2D); glDisable(GL_TEXTURE_2D);
glDisable(GL_LIGHTING); glDisable(GL_LIGHTING);
//GLC_Context::current()->glcEnableLighting(false);
} }
@ -182,19 +178,8 @@ void GLC_PointSprite::render(const GLC_RenderProperties& renderProperties)
} }
// Point sprite set up // Point sprite set up
void GLC_PointSprite::glDraw(const GLC_RenderProperties&) void GLC_PointSprite::glDraw(const GLC_RenderProperties& renderProperties)
{ {
// Point Display GLC_PointCloud::glDraw(renderProperties);
glBegin(GL_POINTS);
glVertex3f(0.0f,0.0f,0.0f);
glEnd();
// OpenGL error handler
GLenum error= glGetError();
if (error != GL_NO_ERROR)
{
GLC_OpenGlException OpenGlException("GLC_PointSprite::GlDraw ", error);
throw(OpenGlException);
}
} }

View File

@ -22,7 +22,7 @@
*****************************************************************************/ *****************************************************************************/
//! \file glc_pointsprite.h interface for the GLC_PointSprite class. //! \file glc_pointsprite.h interface for the GLC_PointSprite class.
#include "glc_geometry.h" #include "glc_pointcloud.h"
#include <QVector> #include <QVector>
#include "../glc_config.h" #include "../glc_config.h"
@ -37,7 +37,7 @@
/*! An GLC_PointSprite is just a simple 3D Sprite Point*/ /*! An GLC_PointSprite is just a simple 3D Sprite Point*/
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
class GLC_LIB_EXPORT GLC_PointSprite : public GLC_Geometry class GLC_LIB_EXPORT GLC_PointSprite : public GLC_PointCloud
{ {
public: public:
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -48,6 +48,9 @@ public:
/*! The material must exist and had texture*/ /*! The material must exist and had texture*/
GLC_PointSprite(float, GLC_Material*); GLC_PointSprite(float, GLC_Material*);
//! Copy constructor
GLC_PointSprite(const GLC_PointSprite& point);
//! Default destructor //! Default destructor
virtual ~GLC_PointSprite(); virtual ~GLC_PointSprite();
//@} //@}
@ -61,9 +64,6 @@ public:
inline float size() const inline float size() const
{return m_Size;} {return m_Size;}
//! Return the point bounding box
virtual const GLC_BoundingBox& boundingBox(void);
//! Return a copy of the geometry //! Return a copy of the geometry
virtual GLC_Geometry* clone() const; virtual GLC_Geometry* clone() const;

View File

@ -64,6 +64,38 @@ GLC_Geometry* GLC_Polylines::clone() const
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Set Functions // Set Functions
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
GLC_uint GLC_Polylines::addPolyline(const QList<GLC_Point3d>& pointsList)
{
const int pointCount= pointsList.size();
const int size= pointCount * 3;
GLfloatVector data(size);
for (int i= 0; i < pointCount; ++i)
{
const GLC_Point3d currentPoint(pointsList.at(i));
data[i * 3]= static_cast<float>(currentPoint.x());
data[i * 3 + 1]= static_cast<float>(currentPoint.y());
data[i * 3 + 2]= static_cast<float>(currentPoint.z());
}
return GLC_Geometry::m_WireData.addVerticeGroup(data);
}
GLC_uint GLC_Polylines::addPolyline(const QList<GLC_Point3df>& pointsList)
{
const int pointCount= pointsList.size();
const int size= pointCount * 3;
GLfloatVector data(size);
for (int i= 0; i < pointCount; ++i)
{
const GLC_Point3df currentPoint(pointsList.at(i));
data[i * 3]= currentPoint.x();
data[i * 3 + 1]= currentPoint.y();
data[i * 3 + 2]= currentPoint.z();
}
return GLC_Geometry::m_WireData.addVerticeGroup(data);
}
GLC_Polylines& GLC_Polylines::operator=(const GLC_Polylines& polyline) GLC_Polylines& GLC_Polylines::operator=(const GLC_Polylines& polyline)
{ {
if (this != &polyline) if (this != &polyline)

View File

@ -74,10 +74,16 @@ public:
//@{ //@{
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
public: public:
//! Add a Polyline to this wire and returns its id if id are managed //! Add a Polyline to this polylines and returns its id if id are managed
inline GLC_uint addPolyline(const GLfloatVector& data) inline GLC_uint addPolyline(const GLfloatVector& data)
{return GLC_Geometry::m_WireData.addVerticeGroup(data);} {return GLC_Geometry::m_WireData.addVerticeGroup(data);}
//! Add polyline with the given list of points to this polylines and returns its id if id are managed
GLC_uint addPolyline(const QList<GLC_Point3d>& pointsList);
//! Add polyline with the given list of points to this polylines and returns its id if id are managed
GLC_uint addPolyline(const QList<GLC_Point3df>& pointsList);
//! Set this polylines from the given polylines and return a reference of this polylines //! Set this polylines from the given polylines and return a reference of this polylines
GLC_Polylines& operator=(const GLC_Polylines& polyline); GLC_Polylines& operator=(const GLC_Polylines& polyline);
@ -91,7 +97,7 @@ public:
/*! \name OpenGL Functions*/ /*! \name OpenGL Functions*/
//@{ //@{
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
private: protected:
//! Virtual interface for OpenGL Geometry set up. //! Virtual interface for OpenGL Geometry set up.
/*! This Virtual function is implemented here.\n /*! This Virtual function is implemented here.\n

View File

@ -189,13 +189,12 @@ void GLC_PrimitiveGroup::addTrianglesStrip(const IndexList& input, GLC_uint id)
// Set the triangle index offset // Set the triangle index offset
void GLC_PrimitiveGroup::setTrianglesOffset(GLvoid* pOffset) void GLC_PrimitiveGroup::setTrianglesOffset(GLvoid* pOffset)
{ {
m_TrianglesGroupOffseti.pop_back(); //m_TrianglesGroupOffseti.pop_back();
const int size= m_TrianglesGroupOffseti.size(); const int size= m_TrianglesGroupOffseti.size();
for (int i= 0; i < size; ++i) for (int i= 0; i < size; ++i)
{ {
m_TrianglesGroupOffset.append(BUFFER_OFFSET(static_cast<GLsizei>(m_TrianglesGroupOffseti[i]) * sizeof(GLuint) + reinterpret_cast<GLsizeiptr>(pOffset))); m_TrianglesGroupOffset.append(BUFFER_OFFSET(static_cast<GLsizei>(m_TrianglesGroupOffseti[i]) * sizeof(GLuint) + reinterpret_cast<GLsizeiptr>(pOffset)));
} }
m_TrianglesGroupOffseti.clear();
} }
// Set the triangle index offset // Set the triangle index offset
@ -212,13 +211,12 @@ void GLC_PrimitiveGroup::setTrianglesOffseti(int offset)
// Set base triangle strip offset // Set base triangle strip offset
void GLC_PrimitiveGroup::setBaseTrianglesStripOffset(GLvoid* pOffset) void GLC_PrimitiveGroup::setBaseTrianglesStripOffset(GLvoid* pOffset)
{ {
m_StripIndexOffseti.pop_back(); //m_StripIndexOffseti.pop_back();
const int size= m_StripIndexOffseti.size(); const int size= m_StripIndexOffseti.size();
for (int i= 0; i < size; ++i) for (int i= 0; i < size; ++i)
{ {
m_StripIndexOffset.append(BUFFER_OFFSET(static_cast<GLsizei>(m_StripIndexOffseti[i]) * sizeof(GLuint) + reinterpret_cast<GLsizeiptr>(pOffset))); m_StripIndexOffset.append(BUFFER_OFFSET(static_cast<GLsizei>(m_StripIndexOffseti[i]) * sizeof(GLuint) + reinterpret_cast<GLsizeiptr>(pOffset)));
} }
m_StripIndexOffseti.clear();
} }
// Set base triangle strip offset // Set base triangle strip offset
@ -257,13 +255,12 @@ void GLC_PrimitiveGroup::addTrianglesFan(const IndexList& input, GLC_uint id)
// Set base triangle fan offset // Set base triangle fan offset
void GLC_PrimitiveGroup::setBaseTrianglesFanOffset(GLvoid* pOffset) void GLC_PrimitiveGroup::setBaseTrianglesFanOffset(GLvoid* pOffset)
{ {
m_FanIndexOffseti.pop_back(); //m_FanIndexOffseti.pop_back();
const int size= m_FanIndexOffseti.size(); const int size= m_FanIndexOffseti.size();
for (int i= 0; i < size; ++i) for (int i= 0; i < size; ++i)
{ {
m_FanIndexOffset.append(BUFFER_OFFSET(static_cast<GLsizei>(m_FanIndexOffseti[i]) * sizeof(GLuint) + reinterpret_cast<GLsizeiptr>(pOffset))); m_FanIndexOffset.append(BUFFER_OFFSET(static_cast<GLsizei>(m_FanIndexOffseti[i]) * sizeof(GLuint) + reinterpret_cast<GLsizeiptr>(pOffset)));
} }
m_FanIndexOffseti.clear();
} }
// Set base triangle fan offset // Set base triangle fan offset
@ -278,16 +275,14 @@ void GLC_PrimitiveGroup::setBaseTrianglesFanOffseti(int offset)
} }
// Change index to VBO mode // Change index to VBO mode
void GLC_PrimitiveGroup::changeToVboMode() void GLC_PrimitiveGroup::computeVboOffset()
{ {
m_TrianglesGroupOffset.clear(); m_TrianglesGroupOffset.clear();
const int triangleOffsetSize= m_TrianglesGroupOffseti.size(); const int triangleOffsetSize= m_TrianglesGroupOffseti.size();
for (int i= 0; i < triangleOffsetSize; ++i) for (int i= 0; i < triangleOffsetSize; ++i)
{ {
m_TrianglesGroupOffset.append(BUFFER_OFFSET(static_cast<GLsizei>(m_TrianglesGroupOffseti.at(i)) * sizeof(GLuint))); m_TrianglesGroupOffset.append(BUFFER_OFFSET(static_cast<GLsizei>(m_TrianglesGroupOffseti.at(i)) * sizeof(GLuint)));
} }
m_TrianglesGroupOffseti.clear();
m_StripIndexOffset.clear(); m_StripIndexOffset.clear();
const int stripOffsetSize= m_StripIndexOffseti.size(); const int stripOffsetSize= m_StripIndexOffseti.size();
@ -295,7 +290,6 @@ void GLC_PrimitiveGroup::changeToVboMode()
{ {
m_StripIndexOffset.append(BUFFER_OFFSET(static_cast<GLsizei>(m_StripIndexOffseti.at(i)) * sizeof(GLuint))); m_StripIndexOffset.append(BUFFER_OFFSET(static_cast<GLsizei>(m_StripIndexOffseti.at(i)) * sizeof(GLuint)));
} }
m_StripIndexOffseti.clear();
m_FanIndexOffset.clear(); m_FanIndexOffset.clear();
const int fanOffsetSize= m_FanIndexOffseti.size(); const int fanOffsetSize= m_FanIndexOffseti.size();
@ -303,7 +297,6 @@ void GLC_PrimitiveGroup::changeToVboMode()
{ {
m_FanIndexOffset.append(BUFFER_OFFSET(static_cast<GLsizei>(m_FanIndexOffseti.at(i)) * sizeof(GLuint))); m_FanIndexOffset.append(BUFFER_OFFSET(static_cast<GLsizei>(m_FanIndexOffseti.at(i)) * sizeof(GLuint)));
} }
m_FanIndexOffseti.clear();
} }
// Clear the group // Clear the group
@ -345,35 +338,10 @@ QDataStream &operator<<(QDataStream &stream, const GLC_PrimitiveGroup &primitive
OffsetVectori fanIndexOffseti; OffsetVectori fanIndexOffseti;
// Get triangles, strips and fans offset // Get triangles, strips and fans offset
if (GLC_State::vboUsed()) trianglesGroupOffseti= primitiveGroup.m_TrianglesGroupOffseti;
{ stripIndexOffseti= primitiveGroup.m_StripIndexOffseti;
// Convert offset to index fanIndexOffseti= primitiveGroup.m_FanIndexOffseti;
// Triangles offset
const int triangleIndexOffsetSize= primitiveGroup.m_TrianglesGroupOffset.size();
for (int i= 0; i < triangleIndexOffsetSize; ++i)
{
trianglesGroupOffseti.append(static_cast<GLuint>(reinterpret_cast<GLsizeiptr>(primitiveGroup.m_TrianglesGroupOffset.at(i)) / sizeof(GLuint)));
}
// Trips offsets
const int stripIndexOffsetSize= primitiveGroup.m_StripIndexOffset.size();
for (int i= 0; i < stripIndexOffsetSize; ++i)
{
stripIndexOffseti.append(static_cast<GLuint>(reinterpret_cast<GLsizeiptr>(primitiveGroup.m_StripIndexOffset.at(i)) / sizeof(GLuint)));
}
// Fans offsets
const int fanIndexOffsetSize= primitiveGroup.m_FanIndexOffset.size();
for (int i= 0; i < fanIndexOffsetSize; ++i)
{
fanIndexOffseti.append(static_cast<GLuint>(reinterpret_cast<GLsizeiptr>(primitiveGroup.m_FanIndexOffset.at(i)) / sizeof(GLuint)));
}
}
else
{
trianglesGroupOffseti= primitiveGroup.m_TrianglesGroupOffseti;
stripIndexOffseti= primitiveGroup.m_StripIndexOffseti;
fanIndexOffseti= primitiveGroup.m_FanIndexOffseti;
}
// Triangles index // Triangles index
stream << primitiveGroup.m_TrianglesIndexSize; stream << primitiveGroup.m_TrianglesIndexSize;
stream << trianglesGroupOffseti; stream << trianglesGroupOffseti;

View File

@ -28,7 +28,7 @@
#include "../glc_ext.h" #include "../glc_ext.h"
#include "../glc_global.h" #include "../glc_global.h"
#include "glc_config.h" #include "../glc_config.h"
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
//! \class GLC_PrimitiveGroup //! \class GLC_PrimitiveGroup
@ -231,8 +231,8 @@ public:
//! Set base triangle fan offset //! Set base triangle fan offset
void setBaseTrianglesFanOffseti(int); void setBaseTrianglesFanOffseti(int);
//! Change index to VBO mode //! Compute VBO offset
void changeToVboMode(); void computeVboOffset();
//! The mesh wich use this group is finished //! The mesh wich use this group is finished
inline void finish() inline void finish()

View File

@ -36,7 +36,7 @@ GLC_Sphere::GLC_Sphere(double radius)
, m_PhiMin(-glc::PI / 2.0) , m_PhiMin(-glc::PI / 2.0)
, m_PhiMax(glc::PI / 2.0) , m_PhiMax(glc::PI / 2.0)
{ {
createMesh();
} }
@ -49,7 +49,7 @@ GLC_Sphere::GLC_Sphere(const GLC_Sphere & sphere)
, m_PhiMin(sphere.m_PhiMin) , m_PhiMin(sphere.m_PhiMin)
, m_PhiMax(sphere.m_PhiMax) , m_PhiMax(sphere.m_PhiMax)
{ {
createMesh();
} }
GLC_Sphere::~GLC_Sphere() GLC_Sphere::~GLC_Sphere()
@ -92,8 +92,19 @@ void GLC_Sphere::setDiscretion(int TargetDiscret)
} }
} }
void GLC_Sphere::glDraw(const GLC_RenderProperties& renderProperties)
{
if (GLC_Mesh::isEmpty())
{
createMesh();
}
GLC_Mesh::glDraw(renderProperties);
}
void GLC_Sphere::createMesh() void GLC_Sphere::createMesh()
{ {
Q_ASSERT(GLC_Mesh::isEmpty()); Q_ASSERT(GLC_Mesh::isEmpty());
GLfloatVector verticeFloat; GLfloatVector verticeFloat;
@ -153,8 +164,8 @@ void GLC_Sphere::createMesh()
xf= m_Radius * cost * cospp; xf= m_Radius * cost * cospp;
yf= m_Radius * sint * cospp; yf= m_Radius * sint * cospp;
verticeFloat << xi << yi << zi << xf << yf << zf; verticeFloat << xf << yf << zf << xi << yi << zi;
normalsFloat << cost * cosp << sint * cosp << sinp << cost * cospp << sint * cospp << sinpp ; normalsFloat << cost * cospp << sint * cospp << sinpp << cost * cosp << sint * cosp << sinp;
texelVector << static_cast<double>(t) * 1.0 / static_cast<double>(nbThetaSteps) texelVector << static_cast<double>(t) * 1.0 / static_cast<double>(nbThetaSteps)
<< static_cast<double>(p) * 1.0 / static_cast<double>(nbPhiSteps) << static_cast<double>(p) * 1.0 / static_cast<double>(nbPhiSteps)
<< static_cast<double>(t) * 1.0 / static_cast<double>(nbThetaSteps) << static_cast<double>(t) * 1.0 / static_cast<double>(nbThetaSteps)

View File

@ -90,6 +90,17 @@ public:
//@} //@}
//////////////////////////////////////////////////////////////////////
/*! \name OpenGL Functions*/
//@{
//////////////////////////////////////////////////////////////////////
private:
//! Virtual interface for OpenGL Geometry set up.
/*! This Virtual function is implemented here.\n
* Throw GLC_OpenGlException*/
virtual void glDraw(const GLC_RenderProperties&);
//@}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
/*! \name Private services Functions*/ /*! \name Private services Functions*/
//@{ //@{

View File

@ -23,38 +23,55 @@
//! \file glc_wiredata.cpp Implementation for the GLC_WireData class. //! \file glc_wiredata.cpp Implementation for the GLC_WireData class.
#include "glc_wiredata.h" #include "glc_wiredata.h"
#include "glc_bsrep.h"
#include "../glc_ext.h" #include "../glc_ext.h"
#include "../glc_state.h" #include "../glc_state.h"
#include "../glc_exception.h"
// Class chunk id // Class chunk id
quint32 GLC_WireData::m_ChunkId= 0xA706; // Old chunkId = 0xA706
quint32 GLC_WireData::m_ChunkId= 0xA711;
GLC_WireData::GLC_WireData() GLC_WireData::GLC_WireData()
: m_VboId(0) : m_VerticeBuffer()
, m_NextPrimitiveLocalId(1) , m_NextPrimitiveLocalId(1)
, m_Positions() , m_Positions()
, m_ColorBuffer()
, m_Colors()
, m_IndexBuffer(QGLBuffer::IndexBuffer)
, m_IndexVector()
, m_PositionSize(0) , m_PositionSize(0)
, m_ColorSize(0)
, m_pBoundingBox(NULL) , m_pBoundingBox(NULL)
, m_VerticeGrouprSizes() , m_VerticeGrouprSizes()
, m_VerticeGroupOffseti()
, m_VerticeGroupOffset() , m_VerticeGroupOffset()
, m_VerticeGroupId() , m_VerticeGroupId()
, m_VerticeGroupCount(0) , m_VerticeGroupCount(0)
, m_UseVbo(false)
{ {
} }
GLC_WireData::GLC_WireData(const GLC_WireData& data) GLC_WireData::GLC_WireData(const GLC_WireData& data)
: m_VboId(0) : m_VerticeBuffer()
, m_NextPrimitiveLocalId(data.m_NextPrimitiveLocalId) , m_NextPrimitiveLocalId(data.m_NextPrimitiveLocalId)
, m_Positions(data.positionVector()) , m_Positions(data.positionVector())
, m_ColorBuffer()
, m_Colors(data.colorVector())
, m_IndexBuffer(QGLBuffer::IndexBuffer)
, m_IndexVector(data.indexVector())
, m_PositionSize(data.m_PositionSize) , m_PositionSize(data.m_PositionSize)
, m_ColorSize(data.m_ColorSize)
, m_pBoundingBox(NULL) , m_pBoundingBox(NULL)
, m_VerticeGrouprSizes(data.m_VerticeGrouprSizes) , m_VerticeGrouprSizes(data.m_VerticeGrouprSizes)
, m_VerticeGroupOffseti(data.m_VerticeGroupOffseti)
, m_VerticeGroupOffset(data.m_VerticeGroupOffset) , m_VerticeGroupOffset(data.m_VerticeGroupOffset)
, m_VerticeGroupId(data.m_VerticeGroupId) , m_VerticeGroupId(data.m_VerticeGroupId)
, m_VerticeGroupCount(data.m_VerticeGroupCount) , m_VerticeGroupCount(data.m_VerticeGroupCount)
, m_UseVbo(data.m_UseVbo)
{ {
if (NULL != data.m_pBoundingBox) if (NULL != data.m_pBoundingBox)
{ {
@ -70,15 +87,20 @@ GLC_WireData& GLC_WireData::operator=(const GLC_WireData& data)
clear(); clear();
m_NextPrimitiveLocalId= data.m_NextPrimitiveLocalId; m_NextPrimitiveLocalId= data.m_NextPrimitiveLocalId;
m_Positions= data.positionVector(); m_Positions= data.positionVector();
m_Colors= data.colorVector();
m_IndexVector= data.indexVector();
m_PositionSize= data.m_PositionSize; m_PositionSize= data.m_PositionSize;
m_ColorSize= data.m_ColorSize;
if (NULL != data.m_pBoundingBox) if (NULL != data.m_pBoundingBox)
{ {
m_pBoundingBox= new GLC_BoundingBox(*(data.m_pBoundingBox)); m_pBoundingBox= new GLC_BoundingBox(*(data.m_pBoundingBox));
} }
m_VerticeGrouprSizes= data.m_VerticeGrouprSizes; m_VerticeGrouprSizes= data.m_VerticeGrouprSizes;
m_VerticeGroupOffseti= data.m_VerticeGroupOffseti;
m_VerticeGroupOffset= data.m_VerticeGroupOffset; m_VerticeGroupOffset= data.m_VerticeGroupOffset;
m_VerticeGroupId= data.m_VerticeGroupId; m_VerticeGroupId= data.m_VerticeGroupId;
m_VerticeGroupCount= data.m_VerticeGroupCount; m_VerticeGroupCount= data.m_VerticeGroupCount;
m_UseVbo= data.m_UseVbo;
} }
return *this; return *this;
} }
@ -86,13 +108,6 @@ GLC_WireData& GLC_WireData::operator=(const GLC_WireData& data)
GLC_WireData::~GLC_WireData() GLC_WireData::~GLC_WireData()
{ {
clear(); clear();
// Delete Main Vbo ID
if (0 != m_VboId)
{
glDeleteBuffers(1, &m_VboId);
m_VboId= 0;
}
} }
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Get Functions // Get Functions
@ -107,18 +122,19 @@ quint32 GLC_WireData::chunckID()
GLfloatVector GLC_WireData::positionVector() const GLfloatVector GLC_WireData::positionVector() const
{ {
if (0 != m_VboId) if (m_VerticeBuffer.isCreated())
{ {
Q_ASSERT((NULL != QGLContext::currentContext()) && QGLContext::currentContext()->isValid());
// VBO created get data from VBO // VBO created get data from VBO
const int sizeOfVbo= m_PositionSize; const int sizeOfVbo= m_PositionSize;
const GLsizeiptr dataSize= sizeOfVbo * sizeof(float); const GLsizeiptr dataSize= sizeOfVbo * sizeof(float);
GLfloatVector positionVector(sizeOfVbo); GLfloatVector positionVector(sizeOfVbo);
glBindBuffer(GL_ARRAY_BUFFER, m_VboId); const_cast<QGLBuffer&>(m_VerticeBuffer).bind();
GLvoid* pVbo = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_ONLY); GLvoid* pVbo = const_cast<QGLBuffer&>(m_VerticeBuffer).map(QGLBuffer::ReadOnly);
memcpy(positionVector.data(), pVbo, dataSize); memcpy(positionVector.data(), pVbo, dataSize);
glUnmapBuffer(GL_ARRAY_BUFFER); const_cast<QGLBuffer&>(m_VerticeBuffer).unmap();
glBindBuffer(GL_ARRAY_BUFFER, 0); const_cast<QGLBuffer&>(m_VerticeBuffer).release();
return positionVector; return positionVector;
} }
else else
@ -127,6 +143,51 @@ GLfloatVector GLC_WireData::positionVector() const
} }
} }
// Return the color Vector
GLfloatVector GLC_WireData::colorVector() const
{
if (m_ColorBuffer.isCreated())
{
// VBO created get data from VBO
const int sizeOfVbo= m_ColorSize;
const GLsizeiptr dataSize= sizeOfVbo * sizeof(GLfloat);
GLfloatVector normalVector(sizeOfVbo);
const_cast<QGLBuffer&>(m_ColorBuffer).bind();
GLvoid* pVbo = const_cast<QGLBuffer&>(m_ColorBuffer).map(QGLBuffer::ReadOnly);
memcpy(normalVector.data(), pVbo, dataSize);
const_cast<QGLBuffer&>(m_ColorBuffer).unmap();
const_cast<QGLBuffer&>(m_ColorBuffer).release();
return normalVector;
}
else
{
return m_Colors;
}
}
QVector<GLuint> GLC_WireData::indexVector() const
{
if (m_IndexBuffer.isCreated())
{
// VBO created get data from VBO
const int sizeOfIbo= m_PositionSize / 3;
const GLsizeiptr dataSize= sizeOfIbo * sizeof(GLuint);
QVector<GLuint> indexVector(sizeOfIbo);
const_cast<QGLBuffer&>(m_IndexBuffer).bind();
GLvoid* pIbo = const_cast<QGLBuffer&>(m_IndexBuffer).map(QGLBuffer::ReadOnly);
memcpy(indexVector.data(), pIbo, dataSize);
const_cast<QGLBuffer&>(m_IndexBuffer).unmap();
const_cast<QGLBuffer&>(m_IndexBuffer).release();
return indexVector;
}
else
{
return m_IndexVector;
}
}
GLC_BoundingBox& GLC_WireData::boundingBox() GLC_BoundingBox& GLC_WireData::boundingBox()
{ {
@ -141,10 +202,26 @@ GLC_BoundingBox& GLC_WireData::boundingBox()
else else
{ {
const int max= m_Positions.size(); const int max= m_Positions.size();
for (int i= 0; i < max; i= i + 3) if (max == 3) // Only One point
{ {
GLC_Point3d point(m_Positions[i], m_Positions[i + 1], m_Positions[i + 2]); const double delta= 1e-2;
m_pBoundingBox->combine(point); GLC_Point3d lower(m_Positions[0] - delta,
m_Positions[1] - delta,
m_Positions[2] - delta);
GLC_Point3d upper(m_Positions[0] + delta,
m_Positions[1] + delta,
m_Positions[2] + delta);
m_pBoundingBox->combine(lower);
m_pBoundingBox->combine(upper);
}
else
{
for (int i= 0; i < max; i= i + 3)
{
GLC_Point3d point(m_Positions[i], m_Positions[i + 1], m_Positions[i + 2]);
m_pBoundingBox->combine(point);
}
} }
} }
@ -166,12 +243,12 @@ GLC_uint GLC_WireData::addVerticeGroup(const GLfloatVector& floatVector)
m_VerticeGrouprSizes.append(static_cast<GLsizei>(floatVector.size() / 3)); m_VerticeGrouprSizes.append(static_cast<GLsizei>(floatVector.size() / 3));
if (m_VerticeGroupOffset.isEmpty()) if (m_VerticeGroupOffseti.isEmpty())
{ {
m_VerticeGroupOffset.append(0); m_VerticeGroupOffseti.append(0);
} }
int offset= m_VerticeGroupOffset.last() + m_VerticeGrouprSizes.last(); int offset= m_VerticeGroupOffseti.last() + m_VerticeGrouprSizes.last();
m_VerticeGroupOffset.append(offset); m_VerticeGroupOffseti.append(offset);
// The Polyline id // The Polyline id
m_VerticeGroupId.append(m_NextPrimitiveLocalId); m_VerticeGroupId.append(m_NextPrimitiveLocalId);
@ -180,6 +257,7 @@ GLC_uint GLC_WireData::addVerticeGroup(const GLfloatVector& floatVector)
void GLC_WireData::clear() void GLC_WireData::clear()
{ {
m_VerticeBuffer.destroy();
m_NextPrimitiveLocalId= 1; m_NextPrimitiveLocalId= 1;
m_Positions.clear(); m_Positions.clear();
m_PositionSize= 0; m_PositionSize= 0;
@ -187,27 +265,54 @@ void GLC_WireData::clear()
m_pBoundingBox= NULL; m_pBoundingBox= NULL;
m_VerticeGrouprSizes.clear(); m_VerticeGrouprSizes.clear();
m_VerticeGroupOffset.clear(); m_VerticeGroupOffseti.clear();
m_VerticeGroupId.clear(); m_VerticeGroupId.clear();
m_VerticeGroupCount= 0; m_VerticeGroupCount= 0;
} }
void GLC_WireData::copyVboToClientSide() void GLC_WireData::copyVboToClientSide()
{ {
if ((0 != m_VboId) && m_Positions.isEmpty()) if (m_VerticeBuffer.isCreated() && m_Positions.isEmpty())
{ {
m_Positions= positionVector(); m_Positions= positionVector();
if (m_ColorBuffer.isCreated() && m_Colors.isEmpty())
{
m_Colors= colorVector();
}
m_IndexVector= indexVector();
} }
} }
void GLC_WireData::releaseVboClientSide(bool update) void GLC_WireData::releaseVboClientSide(bool update)
{ {
if ((0 != m_VboId) && !m_Positions.isEmpty()) if (m_VerticeBuffer.isCreated() && !m_Positions.isEmpty())
{ {
if (update) finishVbo(); if (update) finishVbo();
} }
} }
void GLC_WireData::setVboUsage(bool usage)
{
m_UseVbo= usage;
if (!isEmpty())
{
if (m_UseVbo && (m_PositionSize != 0) && (!m_Positions.isEmpty())&& (!m_VerticeBuffer.isCreated()))
{
finishVbo();
}
else if (!m_UseVbo && m_VerticeBuffer.isCreated())
{
m_Positions= positionVector();
m_VerticeBuffer.destroy();
m_Colors= colorVector();
m_ColorBuffer.destroy();
m_IndexVector= indexVector();
m_IndexBuffer.destroy();
}
}
}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// OpenGL Functions // OpenGL Functions
@ -215,82 +320,212 @@ void GLC_WireData::releaseVboClientSide(bool update)
void GLC_WireData::finishVbo() void GLC_WireData::finishVbo()
{ {
createVBOs(); Q_ASSERT((NULL != QGLContext::currentContext()) && QGLContext::currentContext()->isValid());
useVBO(true); if (!m_VerticeBuffer.isCreated())
{
m_VerticeBuffer.create();
}
if ((m_Colors.size() > 0) && !m_ColorBuffer.isCreated())
{
m_ColorBuffer.create();
}
if (!m_IndexBuffer.isCreated())
{
m_IndexBuffer.create();
}
fillVBOs(); fillVBOs();
useVBO(false);
m_PositionSize= m_Positions.size(); m_PositionSize= m_Positions.size();
m_Positions.clear(); m_Positions.clear();
m_IndexVector.clear();
if (m_ColorBuffer.isCreated())
{
m_ColorSize= m_Colors.size();
m_Colors.clear();
}
} }
void GLC_WireData::useVBO(bool use) void GLC_WireData::useVBO(GLC_WireData::VboType type, bool use)
{ {
if (use) if (use)
{ {
glBindBuffer(GL_ARRAY_BUFFER, m_VboId); }
// Chose the right VBO
if (type == GLC_WireData::GLC_Vertex)
{
if (!m_VerticeBuffer.bind())
{
GLC_Exception exception("GLC_WireData::useVBO Failed to bind vertex buffer");
throw(exception);
}
}
else if (type == GLC_WireData::GLC_Color)
{
Q_ASSERT(m_ColorSize > 0);
if (!m_ColorBuffer.bind())
{
GLC_Exception exception("GLC_WireData::useVBO Failed to bind color buffer");
throw(exception);
}
}
else if ((type == GLC_WireData::GLC_Index) && m_IndexBuffer.isCreated())
{
if (!m_IndexBuffer.bind())
{
GLC_Exception exception("GLC_WireData::useVBO Failed to bind index buffer");
throw(exception);
}
}
}
else else
{ {
// Unbind VBO QGLBuffer::release(QGLBuffer::VertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, 0); QGLBuffer::release(QGLBuffer::IndexBuffer);
} }
} }
void GLC_WireData::glDraw(const GLC_RenderProperties&, GLenum mode) void GLC_WireData::glDraw(const GLC_RenderProperties&, GLenum mode)
{ {
Q_ASSERT((NULL != QGLContext::currentContext()) && QGLContext::currentContext()->isValid());
Q_ASSERT(!isEmpty()); Q_ASSERT(!isEmpty());
const bool vboIsUsed= GLC_State::vboUsed();
if (vboIsUsed && ((m_PositionSize == 0) || (0 == m_VboId))) const bool vboIsUsed= m_UseVbo && GLC_State::vboSupported();
if (vboIsUsed && ((m_PositionSize == 0) || !m_VerticeBuffer.isCreated()))
{ {
finishOffset();
buidIndex();
finishVbo(); finishVbo();
} }
else if (m_PositionSize == 0) else if (!vboIsUsed && (m_PositionSize == 0))
{ {
finishOffset();
buidIndex();
m_PositionSize= m_Positions.size(); m_PositionSize= m_Positions.size();
m_ColorSize= m_Colors.size();
} }
// Activate VBO or Vertex Array // Activate VBO or Vertex Array
if (vboIsUsed) if (vboIsUsed)
{ {
useVBO(true); activateVboAndIbo();
glVertexPointer(3, GL_FLOAT, 0, 0); glVertexPointer(3, GL_FLOAT, 0, 0);
glEnableClientState(GL_VERTEX_ARRAY);
if (m_ColorSize > 0)
{
glColorPointer(4, GL_FLOAT, 0, 0);
glEnableClientState(GL_COLOR_ARRAY);
}
// Render polylines
for (int i= 0; i < m_VerticeGroupCount; ++i)
{
glDrawElements(mode, m_VerticeGrouprSizes.at(i), GL_UNSIGNED_INT, m_VerticeGroupOffset.at(i));
}
useVBO(GLC_WireData::GLC_Index, false);
} }
else else
{ {
glVertexPointer(3, GL_FLOAT, 0, m_Positions.data()); glVertexPointer(3, GL_FLOAT, 0, m_Positions.data());
} glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY); if (m_ColorSize > 0)
{
glColorPointer(4, GL_FLOAT, 0, m_Colors.data());
glEnableClientState(GL_COLOR_ARRAY);
}
// Render polylines
for (int i= 0; i < m_VerticeGroupCount; ++i)
{
glDrawElements(mode, m_VerticeGrouprSizes.at(i), GL_UNSIGNED_INT, &(m_IndexVector.data()[m_VerticeGroupOffseti.at(i)]));
}
// Render polylines
for (int i= 0; i < m_VerticeGroupCount; ++i)
{
glDrawArrays(mode, m_VerticeGroupOffset.at(i), m_VerticeGrouprSizes.at(i));
} }
// Desactivate VBO or Vertex Array if (m_ColorSize > 0)
if (vboIsUsed)
{ {
useVBO(false); glDisableClientState(GL_COLOR_ARRAY);
} }
glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_VERTEX_ARRAY);
}
void GLC_WireData::createVBOs() if (vboIsUsed)
{
// Create position VBO
if (0 == m_VboId)
{ {
glGenBuffers(1, &m_VboId); QGLBuffer::release(QGLBuffer::IndexBuffer);
QGLBuffer::release(QGLBuffer::VertexBuffer);
} }
} }
void GLC_WireData::fillVBOs() void GLC_WireData::fillVBOs()
{ {
const GLsizei dataNbr= static_cast<GLsizei>(m_Positions.size()); {
const GLsizeiptr dataSize= dataNbr * sizeof(GLfloat); Q_ASSERT(m_VerticeBuffer.isCreated());
glBufferData(GL_ARRAY_BUFFER, dataSize, m_Positions.data(), GL_STATIC_DRAW); useVBO(GLC_WireData::GLC_Vertex, true);
const GLsizei dataNbr= static_cast<GLsizei>(m_Positions.size());
const GLsizeiptr dataSize= dataNbr * sizeof(GLfloat);
m_VerticeBuffer.allocate(m_Positions.data(), dataSize);
}
{
Q_ASSERT(m_IndexBuffer.isCreated());
useVBO(GLC_WireData::GLC_Index, true);
const GLsizei dataNbr= static_cast<GLsizei>(m_IndexVector.size());
const GLsizeiptr dataSize= dataNbr * sizeof(GLuint);
m_IndexBuffer.allocate(m_IndexVector.data(), dataSize);
}
if (m_ColorBuffer.isCreated())
{
useVBO(GLC_WireData::GLC_Color, true);
const GLsizei dataNbr= static_cast<GLsizei>(m_Colors.size());
const GLsizeiptr dataSize= dataNbr * sizeof(GLfloat);
m_ColorBuffer.allocate(m_Colors.data(), dataSize);
}
}
void GLC_WireData::buidIndex()
{
const int size= m_Positions.size();
m_IndexVector.resize(size);
for (int i= 0; i < size; ++i)
{
m_IndexVector[i]= i;
}
}
void GLC_WireData::activateVboAndIbo()
{
// Activate Vertices VBO
useVBO(GLC_WireData::GLC_Vertex, true);
glVertexPointer(3, GL_FLOAT, 0, 0);
glEnableClientState(GL_VERTEX_ARRAY);
// Activate Color VBO if needed
if (m_ColorSize > 0)
{
useVBO(GLC_WireData::GLC_Color, true);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE);
glColorPointer(4, GL_FLOAT, 0, 0);
glEnableClientState(GL_COLOR_ARRAY);
}
// Activate index Buffer object
useVBO(GLC_WireData::GLC_Index, true);
}
void GLC_WireData::finishOffset()
{
m_VerticeGroupOffseti.remove(m_VerticeGroupOffseti.size() - 1);
m_VerticeGroupOffset.clear();
const int offsetSize= m_VerticeGroupOffseti.size();
for (int i= 0; i < offsetSize; ++i)
{
m_VerticeGroupOffset.append(BUFFER_OFFSET(static_cast<GLsizei>(m_VerticeGroupOffseti.at(i)) * sizeof(GLuint)));
}
} }
QDataStream &operator<<(QDataStream &stream, const GLC_WireData &wireData) QDataStream &operator<<(QDataStream &stream, const GLC_WireData &wireData)
@ -303,10 +538,14 @@ QDataStream &operator<<(QDataStream &stream, const GLC_WireData &wireData)
stream << wireData.m_PositionSize; stream << wireData.m_PositionSize;
stream << wireData.m_VerticeGrouprSizes; stream << wireData.m_VerticeGrouprSizes;
stream << wireData.m_VerticeGroupOffset; stream << wireData.m_VerticeGroupOffseti;
stream << wireData.m_VerticeGroupId; stream << wireData.m_VerticeGroupId;
stream << wireData.m_VerticeGroupCount; stream << wireData.m_VerticeGroupCount;
// New version Data
stream << wireData.colorVector();
stream << wireData.m_ColorSize;
return stream; return stream;
} }
@ -314,7 +553,7 @@ QDataStream &operator>>(QDataStream &stream, GLC_WireData &wireData)
{ {
quint32 chunckId; quint32 chunckId;
stream >> chunckId; stream >> chunckId;
Q_ASSERT(chunckId == GLC_WireData::m_ChunkId); Q_ASSERT((chunckId == GLC_WireData::m_ChunkId) || chunckId == 0xA706);
wireData.clear(); wireData.clear();
stream >> wireData.m_NextPrimitiveLocalId; stream >> wireData.m_NextPrimitiveLocalId;
@ -322,9 +561,16 @@ QDataStream &operator>>(QDataStream &stream, GLC_WireData &wireData)
stream >> wireData.m_PositionSize; stream >> wireData.m_PositionSize;
stream >> wireData.m_VerticeGrouprSizes; stream >> wireData.m_VerticeGrouprSizes;
stream >> wireData.m_VerticeGroupOffset; stream >> wireData.m_VerticeGroupOffseti;
stream >> wireData.m_VerticeGroupId; stream >> wireData.m_VerticeGroupId;
stream >> wireData.m_VerticeGroupCount; stream >> wireData.m_VerticeGroupCount;
if (chunckId == GLC_WireData::m_ChunkId)
{
// New version Data
stream >> wireData.m_Colors;
stream >> wireData.m_ColorSize;
}
return stream; return stream;
} }

View File

@ -25,6 +25,8 @@
#define GLC_WIREDATA_H_ #define GLC_WIREDATA_H_
#include <QColor> #include <QColor>
#include <QGLBuffer>
#include "../glc_global.h" #include "../glc_global.h"
#include "../glc_boundingbox.h" #include "../glc_boundingbox.h"
#include "../shading/glc_renderproperties.h" #include "../shading/glc_renderproperties.h"
@ -40,6 +42,14 @@ class GLC_LIB_EXPORT GLC_WireData
friend GLC_LIB_EXPORT QDataStream &operator<<(QDataStream &, const GLC_WireData &); friend GLC_LIB_EXPORT QDataStream &operator<<(QDataStream &, const GLC_WireData &);
friend GLC_LIB_EXPORT QDataStream &operator>>(QDataStream &, GLC_WireData &); friend GLC_LIB_EXPORT QDataStream &operator>>(QDataStream &, GLC_WireData &);
//! Enum of VBO TYPE
enum VboType
{
GLC_Vertex= 30,
GLC_Color,
GLC_Index
};
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
/*! @name Constructor / Destructor */ /*! @name Constructor / Destructor */
//@{ //@{
@ -69,6 +79,12 @@ public:
//! Return this wire data Position Vector //! Return this wire data Position Vector
GLfloatVector positionVector() const; GLfloatVector positionVector() const;
//! Return the color Vector
GLfloatVector colorVector() const;
//! Return the unique index vector
QVector<GLuint> indexVector() const;
//! Return true if this wire data is empty //! Return true if this wire data is empty
inline bool isEmpty() const inline bool isEmpty() const
{return ((m_PositionSize == 0) && m_Positions.isEmpty());} {return ((m_PositionSize == 0) && m_Positions.isEmpty());}
@ -82,12 +98,15 @@ public:
//! Return the vertice group offset from the given index //! Return the vertice group offset from the given index
inline GLuint verticeGroupOffset(int index) const inline GLuint verticeGroupOffset(int index) const
{return m_VerticeGroupOffset.at(index);} {return m_VerticeGroupOffseti.at(index);}
//! Return the vertice group size from the given index //! Return the vertice group size from the given index
inline GLsizei verticeGroupSize(int index) const inline GLsizei verticeGroupSize(int index) const
{return m_VerticeGrouprSizes.at(index);} {return m_VerticeGrouprSizes.at(index);}
//! Return true if this wire data use indexed colors
inline bool useIndexdColors() const
{return (m_ColorSize > 0) || (m_Colors.size() > 0);}
//@} //@}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -98,6 +117,10 @@ public:
//! Add a Polyline to this wire and returns its id if id are managed //! Add a Polyline to this wire and returns its id if id are managed
GLC_uint addVerticeGroup(const GLfloatVector&); GLC_uint addVerticeGroup(const GLfloatVector&);
//! Add Colors
inline void addColors(const GLfloatVector& colors)
{m_Colors+= colors;}
//! Clear the content of this wire Data and makes it empty //! Clear the content of this wire Data and makes it empty
void clear(); void clear();
@ -107,6 +130,9 @@ public:
//! Release client VBO //! Release client VBO
void releaseVboClientSide(bool update= false); void releaseVboClientSide(bool update= false);
//! Set VBO usage
void setVboUsage(bool usage);
//@} //@}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -118,18 +144,25 @@ public:
void finishVbo(); void finishVbo();
//! Set vbo usage of this wire data //! Set vbo usage of this wire data
void useVBO(bool usage); void useVBO(GLC_WireData::VboType type, bool usage);
//! Render this wire data using Opengl //! Render this wire data using Opengl
/*! The mode can be : GL_POINTS, GL_LINE_STRIP, GL_LINE_LOOP GL_LINES*/ /*! The mode can be : GL_POINTS, GL_LINE_STRIP, GL_LINE_LOOP GL_LINES*/
void glDraw(const GLC_RenderProperties&, GLenum mode); void glDraw(const GLC_RenderProperties&, GLenum mode);
private: private:
//! Create this wire data VBO id
void createVBOs();
//! Fill this wire data VBO from memmory //! Fill this wire data VBO from memmory
void fillVBOs(); void fillVBOs();
//! Built index
void buidIndex();
//! Activate VBO and IBO
void activateVboAndIbo();
//! Finish offset
void finishOffset();
//@} //@}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -137,7 +170,7 @@ private:
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
private: private:
//! VBO ID //! VBO ID
GLuint m_VboId; QGLBuffer m_VerticeBuffer;
//! The next primitive local id //! The next primitive local id
GLC_uint m_NextPrimitiveLocalId; GLC_uint m_NextPrimitiveLocalId;
@ -145,9 +178,24 @@ private:
//! Vertex Position Vector //! Vertex Position Vector
GLfloatVector m_Positions; GLfloatVector m_Positions;
//! Color Buffer
QGLBuffer m_ColorBuffer;
//! Color index
GLfloatVector m_Colors;
//! The Index Buffer
QGLBuffer m_IndexBuffer;
//! The Index Vector
QVector<GLuint> m_IndexVector;
//! The size of the VBO //! The size of the VBO
int m_PositionSize; int m_PositionSize;
//! The size of Color VBO
int m_ColorSize;
//! Wire data bounding box //! Wire data bounding box
GLC_BoundingBox* m_pBoundingBox; GLC_BoundingBox* m_pBoundingBox;
@ -155,7 +203,10 @@ private:
IndexSizes m_VerticeGrouprSizes; IndexSizes m_VerticeGrouprSizes;
//! Vector of vertice group offset //! Vector of vertice group offset
OffsetVectori m_VerticeGroupOffset; OffsetVectori m_VerticeGroupOffseti;
//! VBO Vector of vertice group offset
OffsetVector m_VerticeGroupOffset;
//! Vertice groups id //! Vertice groups id
QList<GLC_uint> m_VerticeGroupId; QList<GLC_uint> m_VerticeGroupId;
@ -163,6 +214,9 @@ private:
//! The number of vertice group //! The number of vertice group
int m_VerticeGroupCount; int m_VerticeGroupCount;
//! VBO usage
bool m_UseVbo;
//! Class chunk id //! Class chunk id
static quint32 m_ChunkId; static quint32 m_ChunkId;
}; };

View File

@ -19,6 +19,7 @@
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/ *****************************************************************************/
//! \file glc_cachemanager.cpp implementation of the GLC_CacheManager class.
#include "glc_cachemanager.h" #include "glc_cachemanager.h"
#include <QtDebug> #include <QtDebug>

View File

@ -0,0 +1,289 @@
/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)
http://glc-lib.sourceforge.net
GLC-lib is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
GLC-lib is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_context.cpp implementation of the GLC_Context class.
#include "glc_context.h"
#include "glc_contextmanager.h"
#include "shading/glc_shader.h"
#include "glc_state.h"
GLC_Context* GLC_Context::m_pCurrentContext= NULL;
GLC_Context::GLC_Context(const QGLFormat& format)
: QGLContext(format)
, m_CurrentMatrixMode()
, m_MatrixStackHash()
, m_ContextSharedData()
, m_UniformShaderData()
, m_LightingIsEnable()
{
qDebug() << "GLC_Context::GLC_Context";
GLC_ContextManager::instance()->addContext(this);
init();
}
GLC_Context::~GLC_Context()
{
qDebug() << "GLC_Context::~GLC_Context()";
GLC_ContextManager::instance()->remove(this);
QHash<GLenum, QStack<GLC_Matrix4x4>* >::iterator iStack= m_MatrixStackHash.begin();
while (iStack != m_MatrixStackHash.end())
{
delete iStack.value();
++iStack;
}
}
//////////////////////////////////////////////////////////////////////
// Get Functions
//////////////////////////////////////////////////////////////////////
GLC_Context* GLC_Context::current()
{
return m_pCurrentContext;
}
//////////////////////////////////////////////////////////////////////
// OpenGL Functions
//////////////////////////////////////////////////////////////////////
void GLC_Context::glcMatrixMode(GLenum mode)
{
Q_ASSERT(QGLContext::isValid());
Q_ASSERT((mode == GL_MODELVIEW) || (mode == GL_PROJECTION));
m_CurrentMatrixMode= mode;
#ifdef GLC_OPENGL_ES_2
#else
glMatrixMode(m_CurrentMatrixMode);
#endif
}
void GLC_Context::glcLoadIdentity()
{
Q_ASSERT(QGLContext::isValid());
m_MatrixStackHash.value(m_CurrentMatrixMode)->top().setToIdentity();
#ifdef GLC_OPENGL_ES_2
m_UniformShaderData.setModelViewProjectionMatrix(m_MatrixStackHash.value(GL_MODELVIEW)->top(), m_MatrixStackHash.value(GL_PROJECTION)->top());
#else
if (GLC_Shader::hasActiveShader())
{
m_UniformShaderData.setModelViewProjectionMatrix(m_MatrixStackHash.value(GL_MODELVIEW)->top(), m_MatrixStackHash.value(GL_PROJECTION)->top());
}
glLoadIdentity();
#endif
}
void GLC_Context::glcPushMatrix()
{
Q_ASSERT(QGLContext::isValid());
m_MatrixStackHash.value(m_CurrentMatrixMode)->push(m_MatrixStackHash.value(m_CurrentMatrixMode)->top());
#ifndef GLC_OPENGL_ES_2
glPushMatrix();
#endif
}
void GLC_Context::glcPopMatrix()
{
Q_ASSERT(QGLContext::isValid());
m_MatrixStackHash.value(m_CurrentMatrixMode)->pop();
#ifdef GLC_OPENGL_ES_2
this->glcLoadMatrix(m_MatrixStackHash.value(m_CurrentMatrixMode)->top());
#else
if (GLC_Shader::hasActiveShader())
{
this->glcLoadMatrix(m_MatrixStackHash.value(m_CurrentMatrixMode)->top());
}
glPopMatrix();
#endif
}
void GLC_Context::glcLoadMatrix(const GLC_Matrix4x4& matrix)
{
m_MatrixStackHash.value(m_CurrentMatrixMode)->top()= matrix;
#ifdef GLC_OPENGL_ES_2
m_UniformShaderData.setModelViewProjectionMatrix(m_MatrixStackHash.value(GL_MODELVIEW)->top(), m_MatrixStackHash.value(GL_PROJECTION)->top());
#else
if (GLC_Shader::hasActiveShader())
{
m_UniformShaderData.setModelViewProjectionMatrix(m_MatrixStackHash.value(GL_MODELVIEW)->top(), m_MatrixStackHash.value(GL_PROJECTION)->top());
}
::glLoadMatrixd(matrix.getData());
#endif
}
void GLC_Context::glcMultMatrix(const GLC_Matrix4x4& matrix)
{
const GLC_Matrix4x4 current= m_MatrixStackHash.value(m_CurrentMatrixMode)->top();
m_MatrixStackHash.value(m_CurrentMatrixMode)->top()= m_MatrixStackHash.value(m_CurrentMatrixMode)->top() * matrix;
#ifdef GLC_OPENGL_ES_2
m_UniformShaderData.setModelViewProjectionMatrix(m_MatrixStackHash.value(GL_MODELVIEW)->top(), m_MatrixStackHash.value(GL_PROJECTION)->top());
#else
if (GLC_Shader::hasActiveShader())
{
m_UniformShaderData.setModelViewProjectionMatrix(m_MatrixStackHash.value(GL_MODELVIEW)->top(), m_MatrixStackHash.value(GL_PROJECTION)->top());
}
::glMultMatrixd(matrix.getData());
#endif
}
void GLC_Context::glcScaled(double x, double y, double z)
{
GLC_Matrix4x4 scale;
scale.setMatScaling(x, y, z);
glcMultMatrix(scale);
}
void GLC_Context::glcOrtho(double left, double right, double bottom, double top, double nearVal, double farVal)
{
GLC_Matrix4x4 orthoMatrix;
double* m= orthoMatrix.setData();
const double tx= - (right + left) / (right - left);
const double ty= - (top + bottom) / (top - bottom);
const double tz= - (farVal + nearVal) / (farVal - nearVal);
m[0]= 2.0 / (right - left);
m[5]= 2.0 / (top - bottom);
m[10]= -2.0 / (farVal - nearVal);
m[12]= tx;
m[13]= ty;
m[14]= tz;
glcMultMatrix(orthoMatrix);
}
void GLC_Context::glcFrustum(double left, double right, double bottom, double top, double nearVal, double farVal)
{
GLC_Matrix4x4 perspMatrix;
double* m= perspMatrix.setData();
const double a= (right + left) / (right - left);
const double b= (top + bottom) / (top - bottom);
const double c= - (farVal + nearVal) / (farVal - nearVal);
const double d= - (2.0 * farVal * nearVal) / (farVal - nearVal);
m[0]= (2.0 * nearVal) / (right - left);
m[5]= (2.0 * nearVal) / (top - bottom);
m[8]= a;
m[9]= b;
m[10]= c;
m[11]= -1.0;
m[14]= d;
m[15]= 0.0;
glcMultMatrix(perspMatrix);
}
void GLC_Context::glcEnableLighting(bool enable)
{
if (enable != m_LightingIsEnable.top())
{
m_LightingIsEnable.top()= enable;
#ifdef GLC_OPENGL_ES_2
m_UniformShaderData.setLightingState(m_LightingIsEnable);
#else
if (GLC_Shader::hasActiveShader())
{
m_UniformShaderData.setLightingState(m_LightingIsEnable.top());
}
if (m_LightingIsEnable.top()) ::glEnable(GL_LIGHTING);
else ::glDisable(GL_LIGHTING);
#endif
}
}
//////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////
void GLC_Context::makeCurrent()
{
QGLContext::makeCurrent();
if (!GLC_State::isValid())
{
GLC_State::init();
}
GLC_ContextManager::instance()->setCurrent(this);
m_pCurrentContext= this;
}
void GLC_Context::doneCurrent()
{
QGLContext::doneCurrent();
GLC_ContextManager::instance()->setCurrent(NULL);
m_pCurrentContext= NULL;
}
bool GLC_Context::chooseContext(const QGLContext* shareContext)
{
qDebug() << "GLC_Context::chooseContext";
const bool success= QGLContext::chooseContext(shareContext);
if (!success)
{
qDebug() << "enable to create context " << this;
}
else if (NULL != shareContext)
{
GLC_Context* pContext= const_cast<GLC_Context*>(dynamic_cast<const GLC_Context*>(shareContext));
Q_ASSERT(NULL != pContext);
m_ContextSharedData= pContext->m_ContextSharedData;
}
else
{
m_ContextSharedData= QSharedPointer<GLC_ContextSharedData>(new GLC_ContextSharedData());
}
return success;
}
//////////////////////////////////////////////////////////////////////
// Private services Functions
//////////////////////////////////////////////////////////////////////
void GLC_Context::init()
{
QStack<GLC_Matrix4x4>* pStack1= new QStack<GLC_Matrix4x4>();
pStack1->push(GLC_Matrix4x4());
m_MatrixStackHash.insert(GL_MODELVIEW, pStack1);
QStack<GLC_Matrix4x4>* pStack2= new QStack<GLC_Matrix4x4>();
pStack2->push(GLC_Matrix4x4());
m_MatrixStackHash.insert(GL_PROJECTION, pStack2);
m_LightingIsEnable.push(false);
}

View File

@ -0,0 +1,196 @@
/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)
http://glc-lib.sourceforge.net
GLC-lib is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
GLC-lib is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_context.h interface for the GLC_Context class.
#ifndef GLC_CONTEXT_H_
#define GLC_CONTEXT_H_
#include <QtOpenGL>
#include <QGLContext>
#include <QGLFormat>
#include <QSharedPointer>
#include <QtDebug>
#include "glc_config.h"
#include "maths/glc_matrix4x4.h"
#include "glc_contextshareddata.h"
#include "glc_uniformshaderdata.h"
class GLC_ContextSharedData;
// OpenGL ES define
#if defined(QT_OPENGL_ES_2)
#define GLC_OPENGL_ES_2 1
#define GL_MODELVIEW 0x1700
#define GL_PROJECTION 0x1701
#endif
//#define GLC_OPENGL_ES_2 1
//////////////////////////////////////////////////////////////////////
//! \class GLC_Context
/*! \brief GLC_Context : Encapsulates OpenGL rendering context*/
/*! The GLC_Context class store all GLC state associated to an OpenGL rendering context.
* This class is also used to simplified OpenGL and OpenGL-ES interoperability
*/
//////////////////////////////////////////////////////////////////////
class GLC_LIB_EXPORT GLC_Context : public QGLContext
{
//////////////////////////////////////////////////////////////////////
/*! @name Constructor / Destructor */
//@{
//////////////////////////////////////////////////////////////////////
public:
GLC_Context(const QGLFormat& format);
virtual ~GLC_Context();
//@}
//////////////////////////////////////////////////////////////////////
/*! \name Get Functions*/
//@{
//////////////////////////////////////////////////////////////////////
public:
//! Return the current context
static GLC_Context* current();
//! Return the model view matrix
inline GLC_Matrix4x4 modelViewMatrix() const
{Q_ASSERT(m_MatrixStackHash.contains(GL_MODELVIEW)); return m_MatrixStackHash.value(GL_MODELVIEW)->top();}
//! Return the projection matrix
inline GLC_Matrix4x4 projectionMatrix() const
{Q_ASSERT(m_MatrixStackHash.contains(GL_PROJECTION)); return m_MatrixStackHash.value(GL_PROJECTION)->top();}
//! Return lighting enable state
inline bool lightingIsEnable() const
{return m_LightingIsEnable.top();}
//@}
//////////////////////////////////////////////////////////////////////
/*! \name OpenGL Functions*/
//@{
//////////////////////////////////////////////////////////////////////
public:
//! Set the matrix mode
void glcMatrixMode(GLenum mode);
//! Replace the current matrix with the identity
void glcLoadIdentity();
//! push and pop the current matrix stack
void glcPushMatrix();
void glcPopMatrix();
//! Replace the current matrix with the specified matrix
void glcLoadMatrix(const GLC_Matrix4x4& matrix);
//! Multiply the current matrix with the specified matrix
void glcMultMatrix(const GLC_Matrix4x4& matrix);
//! Multiply the current matrix by a translation matrix
inline void glcTranslated(double x, double y, double z)
{glcMultMatrix(GLC_Matrix4x4(x, y, z));}
//! Multiply the current matrix by a general scaling matrix
void glcScaled(double x, double y, double z);
//! Multiply the current matrix with an orthographic matrix
void glcOrtho(double left, double right, double bottom, double top, double nearVal, double farVal);
//! Multiply the current matrix by a perspective matrix
void glcFrustum(double left, double right, double bottom, double top, double nearVal, double farVal);
//! Enable lighting
void glcEnableLighting(bool enable);
//@}
//////////////////////////////////////////////////////////////////////
/*! \name Set Functions*/
//@{
//////////////////////////////////////////////////////////////////////
public:
//! Make this context the current one
virtual void makeCurrent();
//! Make no context to be the current one
virtual void doneCurrent();
//! Update uniform variable
inline void updateUniformVariables()
{m_UniformShaderData.updateAll(this);}
//@}
//////////////////////////////////////////////////////////////////////
/*! \name Private services Functions*/
//@{
//////////////////////////////////////////////////////////////////////
protected:
//@{
virtual bool chooseContext(const QGLContext* shareContext= 0);
//@}
//////////////////////////////////////////////////////////////////////
/*! \name Private services Functions*/
//@{
//////////////////////////////////////////////////////////////////////
private:
//@{
//! Init this context state
void init();
//@}
//////////////////////////////////////////////////////////////////////
// Private members
//////////////////////////////////////////////////////////////////////
private:
//! The current matrix mode
GLenum m_CurrentMatrixMode;
//! Mapping between matrixMode and matrix stack
QHash<GLenum, QStack<GLC_Matrix4x4>* > m_MatrixStackHash;
//! The context shared data
QSharedPointer<GLC_ContextSharedData> m_ContextSharedData;
//! The uniform data of the current shader
GLC_UniformShaderData m_UniformShaderData;
//! The current context
static GLC_Context* m_pCurrentContext;
//! Enable lighting state
QStack<bool> m_LightingIsEnable;
//! Lights enable state
QHash<GLenum, bool> m_LightsEnableState;
};
#endif /* GLC_CONTEXT_H_ */

View File

@ -0,0 +1,88 @@
/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)
http://glc-lib.sourceforge.net
GLC-lib is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
GLC-lib is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_contextmanager.cpp implementation of the GLC_ContextManager class.
#include <QtDebug>
#include "glc_contextmanager.h"
#include "glc_state.h"
GLC_ContextManager* GLC_ContextManager::m_pContextManager= NULL;
GLC_ContextManager::GLC_ContextManager()
: m_pCurrentContext(NULL)
, m_SetOfContext()
{
}
GLC_ContextManager::~GLC_ContextManager()
{
}
//////////////////////////////////////////////////////////////////////
// Get Functions
//////////////////////////////////////////////////////////////////////
GLC_ContextManager* GLC_ContextManager::instance()
{
if (NULL == m_pContextManager)
{
m_pContextManager= new GLC_ContextManager();
}
return m_pContextManager;
}
GLC_Context* GLC_ContextManager::currentContext() const
{
return m_pCurrentContext;
}
//////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////
void GLC_ContextManager::addContext(GLC_Context* pContext)
{
Q_ASSERT(!m_SetOfContext.contains(pContext));
m_SetOfContext.insert(pContext);
}
void GLC_ContextManager::remove(GLC_Context* pContext)
{
Q_ASSERT(m_SetOfContext.contains(pContext));
m_SetOfContext.remove(pContext);
if (m_pCurrentContext == pContext)
{
m_pCurrentContext= NULL;
}
}
void GLC_ContextManager::setCurrent(GLC_Context* pContext)
{
Q_ASSERT((NULL == pContext) || m_SetOfContext.contains(pContext));
m_pCurrentContext= pContext;
}

View File

@ -0,0 +1,104 @@
/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)
http://glc-lib.sourceforge.net
GLC-lib is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
GLC-lib is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_contextmanager.h interface for the GLC_ContextManager class.
#ifndef GLC_CONTEXTMANAGER_H_
#define GLC_CONTEXTMANAGER_H_
#include <QSet>
#include "glc_config.h"
class GLC_Context;
//////////////////////////////////////////////////////////////////////
//! \class GLC_ContextManager
/*! \brief GLC_ContextManager : Manager a set of GLC_Context*/
//////////////////////////////////////////////////////////////////////
class GLC_LIB_EXPORT GLC_ContextManager
{
private:
GLC_ContextManager();
public:
virtual ~GLC_ContextManager();
//@}
//////////////////////////////////////////////////////////////////////
/*! \name Get Functions*/
//@{
//////////////////////////////////////////////////////////////////////
public:
//! Return the unique instance of context manager
static GLC_ContextManager* instance();
//! Return the current context
GLC_Context* currentContext() const;
//! Return true if there is a current context
inline bool currentContextExists() const
{return (NULL != m_pCurrentContext);}
//! Return true if this manager has context
inline bool hasContext() const
{return !m_SetOfContext.isEmpty();}
//@}
//////////////////////////////////////////////////////////////////////
/*! \name Set Functions*/
//@{
//////////////////////////////////////////////////////////////////////
public:
//! Add the given context
void addContext(GLC_Context* pContext);
//! Remove the given context
void remove(GLC_Context* pContext);
//! Set the current the given context
void setCurrent(GLC_Context* pContext);
//////////////////////////////////////////////////////////////////////
/*! \name Private services Functions*/
//@{
//////////////////////////////////////////////////////////////////////
private:
//@{
//@}
//////////////////////////////////////////////////////////////////////
// Private members
//////////////////////////////////////////////////////////////////////
private:
//! The unique instance of the context manager
static GLC_ContextManager* m_pContextManager;
//! The current context
GLC_Context* m_pCurrentContext;
//! The Set of context to manage
QSet<GLC_Context*> m_SetOfContext;
};
#endif /* GLC_CONTEXTMANAGER_H_ */

View File

@ -19,16 +19,19 @@
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/ *****************************************************************************/
//! \file glc_openglstate.cpp implementation of the GLC_OpenGLState class. //! \file glc_contextshareddata.cpp implementation of the GLC_ContextSharedData class.
#include "glc_openglstate.h" #include <QtDebug>
GLC_OpenGLState::GLC_OpenGLState() #include "glc_contextshareddata.h"
GLC_ContextSharedData::GLC_ContextSharedData()
{ {
qDebug() << "GLC_ContextSharedData::GLC_ContextSharedData()";
} }
GLC_OpenGLState::~GLC_OpenGLState() GLC_ContextSharedData::~GLC_ContextSharedData()
{ {
qDebug() << "GLC_ContextSharedData::~GLC_ContextSharedData()";
} }

View File

@ -19,16 +19,18 @@
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/ *****************************************************************************/
//! \file glc_openglstatemanager.h interface for the GLC_OpenGLStateManager class. //! \file glc_contextshareddata.h interface for the GLC_ContextSharedData class.
#ifndef GLC_OPENGLSTATEMANAGER_H_ #ifndef GLC_CONTEXTSHAREDDATA_H_
#define GLC_OPENGLSTATEMANAGER_H_ #define GLC_CONTEXTSHAREDDATA_H_
class GLC_OpenGLStateManager #include "glc_config.h"
class GLC_LIB_EXPORT GLC_ContextSharedData
{ {
public: public:
GLC_OpenGLStateManager(); GLC_ContextSharedData();
virtual ~GLC_OpenGLStateManager(); virtual ~GLC_ContextSharedData();
}; };
#endif /* GLC_OPENGLSTATEMANAGER_H_ */ #endif /* GLC_CONTEXTSHAREDDATA_H_ */

View File

@ -26,25 +26,9 @@
#include <QGLContext> #include <QGLContext>
#include <QDebug> #include <QDebug>
#include <QGLShaderProgram> #include <QGLShaderProgram>
#include <QGLBuffer>
#if !defined(Q_OS_MAC) #if !defined(Q_OS_MAC)
// ARB_vertex_buffer_object
PFNGLBINDBUFFERARBPROC glBindBuffer = NULL;
PFNGLDELETEBUFFERSARBPROC glDeleteBuffers = NULL;
PFNGLGENBUFFERSARBPROC glGenBuffers = NULL;
PFNGLISBUFFERARBPROC glIsBuffer = NULL;
PFNGLBUFFERDATAARBPROC glBufferData = NULL;
PFNGLBUFFERSUBDATAARBPROC glBufferSubData = NULL;
PFNGLGETBUFFERSUBDATAARBPROC glGetBufferSubData = NULL;
PFNGLMAPBUFFERARBPROC glMapBuffer = NULL;
PFNGLUNMAPBUFFERARBPROC glUnmapBuffer = NULL;
PFNGLGETBUFFERPARAMETERIVARBPROC glGetBufferParameteriv = NULL;
PFNGLGETBUFFERPOINTERVARBPROC glGetBufferPointerv = NULL;
// glDrawRangElement
//PFNGLDRAWRANGEELEMENTSPROC glDrawRangeElements = NULL;
// glMultiDrawElement
PFNGLMULTIDRAWELEMENTSPROC glMultiDrawElements = NULL;
// GL_point_parameters Point Sprite // GL_point_parameters Point Sprite
PFNGLPOINTPARAMETERFARBPROC glPointParameterf = NULL; PFNGLPOINTPARAMETERFARBPROC glPointParameterf = NULL;
@ -52,7 +36,6 @@ PFNGLPOINTPARAMETERFVARBPROC glPointParameterfv = NULL;
#endif #endif
//const QString glExtension(reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS)));
// Return true if the extension is supported // Return true if the extension is supported
bool glc::extensionIsSupported(const QString& extension) bool glc::extensionIsSupported(const QString& extension)
@ -64,28 +47,10 @@ bool glc::extensionIsSupported(const QString& extension)
// Return true if VBO extension is succesfully loaded // Return true if VBO extension is succesfully loaded
bool glc::loadVboExtension() bool glc::loadVboExtension()
{ {
bool result= true; QGLBuffer buffer;
#if !defined(Q_OS_MAC) bool result= buffer.create();
const QGLContext* pContext= QGLContext::currentContext(); buffer.destroy();
glBindBuffer = (PFNGLBINDBUFFERARBPROC)pContext->getProcAddress(QLatin1String("glBindBuffer"));
glDeleteBuffers = (PFNGLDELETEBUFFERSARBPROC)pContext->getProcAddress(QLatin1String("glDeleteBuffers"));
glGenBuffers = (PFNGLGENBUFFERSARBPROC)pContext->getProcAddress(QLatin1String("glGenBuffers"));
glIsBuffer = (PFNGLISBUFFERARBPROC)pContext->getProcAddress(QLatin1String("glIsBuffer"));
glBufferData = (PFNGLBUFFERDATAARBPROC)pContext->getProcAddress(QLatin1String("glBufferData"));
glBufferSubData = (PFNGLBUFFERSUBDATAARBPROC)pContext->getProcAddress(QLatin1String("glBufferSubData"));
glGetBufferSubData = (PFNGLGETBUFFERSUBDATAARBPROC)pContext->getProcAddress(QLatin1String("glGetBufferSubData"));
glMapBuffer = (PFNGLMAPBUFFERARBPROC)pContext->getProcAddress(QLatin1String("glMapBuffer"));
glUnmapBuffer = (PFNGLUNMAPBUFFERARBPROC)pContext->getProcAddress(QLatin1String("glUnmapBuffer"));
glGetBufferParameteriv = (PFNGLGETBUFFERPARAMETERIVARBPROC)pContext->getProcAddress(QLatin1String("glGetBufferParameteriv"));
glGetBufferPointerv = (PFNGLGETBUFFERPOINTERVARBPROC)pContext->getProcAddress(QLatin1String("glGetBufferPointerv"));
//glDrawRangeElements = (PFNGLDRAWRANGEELEMENTSPROC)pContext->getProcAddress(QLatin1String("glDrawRangeElements"));
glMultiDrawElements = (PFNGLMULTIDRAWELEMENTSPROC)pContext->getProcAddress(QLatin1String("glMultiDrawElements"));
result= glBindBuffer && glDeleteBuffers && glGenBuffers && glIsBuffer && glBufferData && glBufferSubData &&
glGetBufferSubData && glMapBuffer && glUnmapBuffer && glGetBufferParameteriv && glGetBufferPointerv && glMultiDrawElements;// and glDrawRangeElements;
#endif
return result; return result;
} }
// Load GLSL extensions // Load GLSL extensions

View File

@ -30,37 +30,7 @@
// Buffer offset used by VBO // Buffer offset used by VBO
#define BUFFER_OFFSET(i) ((char*)NULL + (i)) #define BUFFER_OFFSET(i) ((char*)NULL + (i))
#if defined(Q_OS_MAC)
#include "gl.h"
#include "glu.h"
#endif
#if defined(Q_OS_WIN32)
#include "GL/gl.h"
#include "GL/glu.h"
#endif
#if defined(Q_OS_LINUX)
#include "GL/glu.h"
#endif
#if !defined(Q_OS_MAC) #if !defined(Q_OS_MAC)
// ARB_vertex_buffer_object
extern PFNGLBINDBUFFERARBPROC glBindBuffer;
extern PFNGLDELETEBUFFERSARBPROC glDeleteBuffers;
extern PFNGLGENBUFFERSARBPROC glGenBuffers;
extern PFNGLISBUFFERARBPROC glIsBuffer;
extern PFNGLBUFFERDATAARBPROC glBufferData;
extern PFNGLBUFFERSUBDATAARBPROC glBufferSubData;
extern PFNGLGETBUFFERSUBDATAARBPROC glGetBufferSubData;
extern PFNGLMAPBUFFERARBPROC glMapBuffer;
extern PFNGLUNMAPBUFFERARBPROC glUnmapBuffer;
extern PFNGLGETBUFFERPARAMETERIVARBPROC glGetBufferParameteriv;
extern PFNGLGETBUFFERPOINTERVARBPROC glGetBufferPointerv;
// glDrawRangElement
//extern PFNGLDRAWRANGEELEMENTSPROC glDrawRangeElements;
// glMultiDrawElement
extern PFNGLMULTIDRAWELEMENTSPROC glMultiDrawElements;
// GL_point_parameters Point Sprite // GL_point_parameters Point Sprite
extern PFNGLPOINTPARAMETERFARBPROC glPointParameterf; extern PFNGLPOINTPARAMETERFARBPROC glPointParameterf;

View File

@ -37,6 +37,7 @@
#include "viewport/glc_reptrackballmover.h" #include "viewport/glc_reptrackballmover.h"
#include "viewport/glc_flymover.h" #include "viewport/glc_flymover.h"
#include "viewport/glc_repflymover.h" #include "viewport/glc_repflymover.h"
#include "viewport/glc_tsrmover.h"
#include "maths/glc_line3d.h" #include "maths/glc_line3d.h"
#include "maths/glc_geomtools.h" #include "maths/glc_geomtools.h"
@ -44,7 +45,6 @@
// init static member // init static member
GLC_Factory* GLC_Factory::m_pFactory= NULL; GLC_Factory* GLC_Factory::m_pFactory= NULL;
QGLContext* GLC_Factory::m_pQGLContext= NULL;
QList<GLC_WorldReaderPlugin*> GLC_Factory::m_WorldReaderPluginList; QList<GLC_WorldReaderPlugin*> GLC_Factory::m_WorldReaderPluginList;
QSet<QString> GLC_Factory::m_SupportedExtensionSet; QSet<QString> GLC_Factory::m_SupportedExtensionSet;
@ -52,15 +52,11 @@ QSet<QString> GLC_Factory::m_SupportedExtensionSet;
// static method // static method
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Return the unique instance of the factory // Return the unique instance of the factory
GLC_Factory* GLC_Factory::instance(const QGLContext *pContext) GLC_Factory* GLC_Factory::instance()
{ {
if(m_pFactory == NULL) if(m_pFactory == NULL)
{ {
m_pFactory= new GLC_Factory(pContext); m_pFactory= new GLC_Factory();
}
else if ((NULL != pContext) && (m_pQGLContext != pContext))
{
m_pQGLContext= const_cast<QGLContext*>(pContext);
} }
return m_pFactory; return m_pFactory;
} }
@ -70,9 +66,8 @@ GLC_Factory* GLC_Factory::instance(const QGLContext *pContext)
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Protected constructor // Protected constructor
GLC_Factory::GLC_Factory(const QGLContext *pContext) GLC_Factory::GLC_Factory()
{ {
m_pQGLContext= (const_cast<QGLContext*>(pContext));
loadPlugins(); loadPlugins();
} }
@ -231,7 +226,7 @@ GLC_World GLC_Factory::createWorldStructureFrom3dxml(QFile &file, bool GetExtRef
if (QFileInfo(file).suffix().toLower() == "3dxml") if (QFileInfo(file).suffix().toLower() == "3dxml")
{ {
GLC_3dxmlToWorld d3dxmlToWorld(m_pQGLContext); GLC_3dxmlToWorld d3dxmlToWorld;
connect(&d3dxmlToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int))); connect(&d3dxmlToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));
pWorld= d3dxmlToWorld.createWorldFrom3dxml(file, true, GetExtRefName); pWorld= d3dxmlToWorld.createWorldFrom3dxml(file, true, GetExtRefName);
} }
@ -253,9 +248,9 @@ GLC_3DRep GLC_Factory::create3DRepFromFile(const QString& fileName) const
{ {
GLC_3DRep rep; GLC_3DRep rep;
if ((QFileInfo(fileName).suffix().toLower() == "3dxml") || (QFileInfo(fileName).suffix().toLower() == "3drep")) if ((QFileInfo(fileName).suffix().toLower() == "3dxml") || (QFileInfo(fileName).suffix().toLower() == "3drep") || (QFileInfo(fileName).suffix().toLower() == "xml"))
{ {
GLC_3dxmlToWorld d3dxmlToWorld(m_pQGLContext); GLC_3dxmlToWorld d3dxmlToWorld;
connect(&d3dxmlToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int))); connect(&d3dxmlToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));
rep= d3dxmlToWorld.create3DrepFrom3dxmlRep(fileName); rep= d3dxmlToWorld.create3DrepFrom3dxmlRep(fileName);
} }
@ -266,7 +261,7 @@ GLC_3DRep GLC_Factory::create3DRepFromFile(const QString& fileName) const
GLC_FileLoader* GLC_Factory::createFileLoader() const GLC_FileLoader* GLC_Factory::createFileLoader() const
{ {
return new GLC_FileLoader(m_pQGLContext); return new GLC_FileLoader;
} }
GLC_Material* GLC_Factory::createMaterial() const GLC_Material* GLC_Factory::createMaterial() const
@ -303,12 +298,12 @@ GLC_Material* GLC_Factory::createMaterial(const QImage &image) const
GLC_Texture* GLC_Factory::createTexture(const QString &textureFullFileName) const GLC_Texture* GLC_Factory::createTexture(const QString &textureFullFileName) const
{ {
return new GLC_Texture(m_pQGLContext, textureFullFileName); return new GLC_Texture(textureFullFileName);
} }
GLC_Texture* GLC_Factory::createTexture(const QImage & image, const QString& imageFileName) const GLC_Texture* GLC_Factory::createTexture(const QImage & image, const QString& imageFileName) const
{ {
return new GLC_Texture(m_pQGLContext, image, imageFileName); return new GLC_Texture(image, imageFileName);
} }
GLC_MoverController GLC_Factory::createDefaultMoverController(const QColor& color, GLC_Viewport* pViewport) GLC_MoverController GLC_Factory::createDefaultMoverController(const QColor& color, GLC_Viewport* pViewport)
@ -371,6 +366,7 @@ GLC_MoverController GLC_Factory::createDefaultMoverController(const QColor& colo
pMover= new GLC_TurnTableMover(pViewport); pMover= new GLC_TurnTableMover(pViewport);
// Add the Turn Table Mover to the controller // Add the Turn Table Mover to the controller
defaultController.addMover(pMover, GLC_MoverController::TurnTable); defaultController.addMover(pMover, GLC_MoverController::TurnTable);
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Fly Mover // Fly Mover
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -383,6 +379,14 @@ GLC_MoverController GLC_Factory::createDefaultMoverController(const QColor& colo
// Add the fly mover to the controller // Add the fly mover to the controller
defaultController.addMover(pMover, GLC_MoverController::Fly); defaultController.addMover(pMover, GLC_MoverController::Fly);
//////////////////////////////////////////////////////////////////////
// Translation, rotation and scaling Mover
//////////////////////////////////////////////////////////////////////
// Create the Turn Table Mover
pMover= new GLC_TsrMover(pViewport);
// Add the Turn Table Mover to the controller
defaultController.addMover(pMover, GLC_MoverController::TSR);
return defaultController; return defaultController;
} }

View File

@ -70,11 +70,11 @@ class GLC_LIB_EXPORT GLC_Factory : public QObject
public: public:
//! Get unique instance of the factory //! Get unique instance of the factory
static GLC_Factory* instance(const QGLContext * pContext= NULL); static GLC_Factory* instance();
protected: protected:
//! Constructor //! Constructor
GLC_Factory(const QGLContext *); GLC_Factory();
public: public:
//! Destructor //! Destructor
~GLC_Factory(); ~GLC_Factory();
@ -84,9 +84,6 @@ public:
//@{ //@{
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
public: public:
//! Return the current factory context
inline QGLContext* context() const
{return m_pQGLContext;}
//! Create a GLC_Point //! Create a GLC_Point
GLC_3DRep createPoint(const GLC_Point3d &coord) const; GLC_3DRep createPoint(const GLC_Point3d &coord) const;
@ -201,9 +198,6 @@ private:
//! The unique instance of the factory //! The unique instance of the factory
static GLC_Factory* m_pFactory; static GLC_Factory* m_pFactory;
//! The QGLContext attached to the factory (rendering context)
static QGLContext* m_pQGLContext;
//! The list off worldReader plugins //! The list off worldReader plugins
static QList<GLC_WorldReaderPlugin*> m_WorldReaderPluginList; static QList<GLC_WorldReaderPlugin*> m_WorldReaderPluginList;

View File

@ -120,7 +120,7 @@ namespace glc
GLC_LIB_EXPORT QString archiveEntryFileName(const QString& archiveString); GLC_LIB_EXPORT QString archiveEntryFileName(const QString& archiveString);
// GLC_Lib version // GLC_Lib version
const QString version("2.1.0"); const QString version("2.2.0");
const QString description("GLC_lib is a Open Source C++ class library that enables the quick creation of an OpenGL application based on QT4."); const QString description("GLC_lib is a Open Source C++ class library that enables the quick creation of an OpenGL application based on QT4.");
}; };

View File

@ -9,11 +9,10 @@ QT += opengl \
core core
#CONFIG += exceptions \ CONFIG += exceptions \
# release \ warn_on
# warn_on
#TARGET = GLC_lib #TARGET = GLC_lib
#VERSION = 2.1.0 #VERSION = 2.2.0
DEFINES += CREATE_GLC_LIB_DLL DEFINES += CREATE_GLC_LIB_DLL
DEFINES += LIB3DS_EXPORTS DEFINES += LIB3DS_EXPORTS
@ -28,6 +27,8 @@ DEPENDPATH += .
INCLUDEPATH += . INCLUDEPATH += .
INCLUDEPATH += ./3rdparty/zlib INCLUDEPATH += ./3rdparty/zlib
RESOURCES += glc_lib.qrc
# Input # Input
HEADERS_QUAZIP += 3rdparty/quazip/crypt.h \ HEADERS_QUAZIP += 3rdparty/quazip/crypt.h \
3rdparty/quazip/ioapi.h \ 3rdparty/quazip/ioapi.h \
@ -145,8 +146,9 @@ HEADERS_GLC_VIEWPORT += viewport/glc_camera.h \
viewport/glc_turntablemover.h \ viewport/glc_turntablemover.h \
viewport/glc_frustum.h \ viewport/glc_frustum.h \
viewport/glc_flymover.h \ viewport/glc_flymover.h \
viewport/glc_repflymover.h viewport/glc_repflymover.h \
viewport/glc_userinput.h \
viewport/glc_tsrmover.h
HEADERS_GLC += glc_global.h \ HEADERS_GLC += glc_global.h \
glc_object.h \ glc_object.h \
@ -163,7 +165,10 @@ HEADERS_GLC += glc_global.h \
glc_log.h \ glc_log.h \
glc_errorlog.h \ glc_errorlog.h \
glc_tracelog.h \ glc_tracelog.h \
glc_openglstate.h glc_context.h \
glc_contextmanager.h \
glc_contextshareddata.h \
glc_uniformshaderdata.h
HEADERS_GLC_3DWIDGET += 3DWidget/glc_3dwidget.h \ HEADERS_GLC_3DWIDGET += 3DWidget/glc_3dwidget.h \
3DWidget/glc_cuttingplane.h \ 3DWidget/glc_cuttingplane.h \
@ -174,10 +179,11 @@ HEADERS_GLC_3DWIDGET += 3DWidget/glc_3dwidget.h \
3DWidget/glc_rotationmanipulator.h \ 3DWidget/glc_rotationmanipulator.h \
3DWidget/glc_axis.h 3DWidget/glc_axis.h
HEADERS_GLC_GLU += glu/glc_glu.h
HEADERS += $${HEADERS_QUAZIP} $${HEADERS_LIB3DS} $${HEADERS_GLC_MATHS} $${HEADERS_GLC_IO} HEADERS += $${HEADERS_QUAZIP} $${HEADERS_LIB3DS} $${HEADERS_GLC_MATHS} $${HEADERS_GLC_IO}
HEADERS += $${HEADERS_GLC} $${HEADERS_GLEXT} $${HEADERS_GLC_SCENEGRAPH} $${HEADERS_GLC_GEOMETRY} HEADERS += $${HEADERS_GLC} $${HEADERS_GLEXT} $${HEADERS_GLC_SCENEGRAPH} $${HEADERS_GLC_GEOMETRY}
HEADERS += $${HEADERS_GLC_SHADING} $${HEADERS_GLC_VIEWPORT} $${HEADERS_GLC_3DWIDGET} HEADERS += $${HEADERS_GLC_SHADING} $${HEADERS_GLC_VIEWPORT} $${HEADERS_GLC_3DWIDGET} $${HEADERS_GLC_GLU}
SOURCES += 3rdparty/zlib/adler32.c \ SOURCES += 3rdparty/zlib/adler32.c \
3rdparty/zlib/compress.c \ 3rdparty/zlib/compress.c \
@ -294,7 +300,9 @@ SOURCES += viewport/glc_camera.cpp \
viewport/glc_turntablemover.cpp \ viewport/glc_turntablemover.cpp \
viewport/glc_frustum.cpp \ viewport/glc_frustum.cpp \
viewport/glc_flymover.cpp \ viewport/glc_flymover.cpp \
viewport/glc_repflymover.cpp viewport/glc_repflymover.cpp \
viewport/glc_userinput.cpp \
viewport/glc_tsrmover.cpp
SOURCES += glc_global.cpp \ SOURCES += glc_global.cpp \
glc_object.cpp \ glc_object.cpp \
@ -310,7 +318,10 @@ SOURCES += glc_global.cpp \
glc_log.cpp \ glc_log.cpp \
glc_errorlog.cpp \ glc_errorlog.cpp \
glc_tracelog.cpp \ glc_tracelog.cpp \
glc_openglstate.cpp glc_context.cpp \
glc_contextmanager.cpp \
glc_contextshareddata.cpp \
glc_uniformshaderdata.cpp
SOURCES += 3DWidget/glc_3dwidget.cpp \ SOURCES += 3DWidget/glc_3dwidget.cpp \
3DWidget/glc_cuttingplane.cpp \ 3DWidget/glc_cuttingplane.cpp \
@ -321,6 +332,7 @@ SOURCES += 3DWidget/glc_3dwidget.cpp \
3DWidget/glc_rotationmanipulator.cpp \ 3DWidget/glc_rotationmanipulator.cpp \
3DWidget/glc_axis.cpp 3DWidget/glc_axis.cpp
SOURCES += glu/glc_project.cpp
# Windows compilation configuration # Windows compilation configuration
win32:CONFIG *= dll win32:CONFIG *= dll
@ -413,12 +425,17 @@ HEADERS_INST = include/GLC_BoundingBox \
include/GLC_ErrorLog \ include/GLC_ErrorLog \
include/GLC_TraceLog \ include/GLC_TraceLog \
include/glcXmlUtil \ include/glcXmlUtil \
include/GLC_OpenGLState \ include/GLC_RenderState \
include/GLC_FileLoader \ include/GLC_FileLoader \
include/GLC_WorldReaderPlugin \ include/GLC_WorldReaderPlugin \
include/GLC_WorldReaderHandler \ include/GLC_WorldReaderHandler \
include/GLC_PointCloud \ include/GLC_PointCloud \
include/GLC_SelectionSet include/GLC_SelectionSet \
include/GLC_UserInput \
include/GLC_TsrMover \
include/GLC_Glu \
include/GLC_Context \
include/GLC_ContextManager
# Linux and macx install configuration # Linux and macx install configuration
@ -439,6 +456,7 @@ unix {
include_glc_shading.path = $${INCLUDE_DIR}/GLC_lib/shading include_glc_shading.path = $${INCLUDE_DIR}/GLC_lib/shading
include_glc_viewport.path = $${INCLUDE_DIR}/GLC_lib/viewport include_glc_viewport.path = $${INCLUDE_DIR}/GLC_lib/viewport
include_glc_3dwidget.path = $${INCLUDE_DIR}/GLC_lib/3DWidget include_glc_3dwidget.path = $${INCLUDE_DIR}/GLC_lib/3DWidget
include_glc_glu.path = $${INCLUDE_DIR}/GLC_lib/glu
} }
# Windows Install configuration # Windows Install configuration
@ -457,6 +475,7 @@ win32 {
include_glc_shading.path = $${INCLUDE_DIR}/shading include_glc_shading.path = $${INCLUDE_DIR}/shading
include_glc_viewport.path = $${INCLUDE_DIR}/viewport include_glc_viewport.path = $${INCLUDE_DIR}/viewport
include_glc_3dwidget.path = $${INCLUDE_DIR}/3DWidget include_glc_3dwidget.path = $${INCLUDE_DIR}/3DWidget
include_glc_glu.path = $${INCLUDE_DIR}/glu
} }
include.files = $${HEADERS_GLC} $${HEADERS_INST} include.files = $${HEADERS_GLC} $${HEADERS_INST}
@ -470,6 +489,7 @@ include_glc_geometry.files= $${HEADERS_GLC_GEOMETRY}
include_glc_shading.files = $${HEADERS_GLC_SHADING} include_glc_shading.files = $${HEADERS_GLC_SHADING}
include_glc_viewport.files = $${HEADERS_GLC_VIEWPORT} include_glc_viewport.files = $${HEADERS_GLC_VIEWPORT}
include_glc_3dwidget.files = $${HEADERS_GLC_3DWIDGET} include_glc_3dwidget.files = $${HEADERS_GLC_3DWIDGET}
include_glc_glu.files = $${HEADERS_GLC_GLU}
# install library # install library
target.path = $${LIB_DIR} target.path = $${LIB_DIR}
@ -477,8 +497,15 @@ target.path = $${LIB_DIR}
# "make install" configuration options # "make install" configuration options
INSTALLS += include_lib3ds include_glext include_quazip include_glc_maths include_glc_io INSTALLS += include_lib3ds include_glext include_quazip include_glc_maths include_glc_io
INSTALLS += include_glc_scengraph include_glc_geometry include_glc_shading include_glc_viewport INSTALLS += include_glc_scengraph include_glc_geometry include_glc_shading include_glc_viewport
INSTALLS += include_glc_3dwidget INSTALLS += include_glc_3dwidget include_glc_glu
INSTALLS += target INSTALLS += target
INSTALLS +=include INSTALLS +=include
OTHER_FILES += \
qtc_packaging/debian_harmattan/rules \
qtc_packaging/debian_harmattan/README \
qtc_packaging/debian_harmattan/copyright \
qtc_packaging/debian_harmattan/control \
qtc_packaging/debian_harmattan/compat \
qtc_packaging/debian_harmattan/changelog

View File

@ -0,0 +1,6 @@
<RCC>
<qresource prefix="/GLC_lib_Shaders" >
<file alias="default_frag">shading/shaders/default.frag</file>
<file alias="default_vert">shading/shaders/default.vert</file>
</qresource>
</RCC>

View File

@ -48,6 +48,7 @@ GLC_CacheManager GLC_State::m_CacheManager;
bool GLC_State::m_IsSpacePartitionningActivated= false; bool GLC_State::m_IsSpacePartitionningActivated= false;
bool GLC_State::m_IsFrustumCullingActivated= false; bool GLC_State::m_IsFrustumCullingActivated= false;
bool GLC_State::m_IsValid= false;
GLC_State::~GLC_State() GLC_State::~GLC_State()
{ {
@ -145,13 +146,24 @@ bool GLC_State::isFrustumCullingActivated()
void GLC_State::init() void GLC_State::init()
{ {
setVboSupport(); if (!m_IsValid)
setGlslSupport(); {
setPointSpriteSupport(); Q_ASSERT((NULL != QGLContext::currentContext()) && QGLContext::currentContext()->isValid());
setFrameBufferSupport(); setVboSupport();
m_Version= (char *) glGetString(GL_VERSION); setGlslSupport();
m_Vendor= (char *) glGetString(GL_VENDOR); setPointSpriteSupport();
m_Renderer= (char *) glGetString(GL_RENDERER); setFrameBufferSupport();
m_Version= (char *) glGetString(GL_VERSION);
m_Vendor= (char *) glGetString(GL_VENDOR);
m_Renderer= (char *) glGetString(GL_RENDERER);
m_IsValid= true;
}
}
bool GLC_State::isValid()
{
return m_IsValid;
} }
void GLC_State::setVboSupport() void GLC_State::setVboSupport()

View File

@ -103,6 +103,9 @@ public:
//! Return true if frustum culling is activated //! Return true if frustum culling is activated
static bool isFrustumCullingActivated(); static bool isFrustumCullingActivated();
//! Return true valid
static bool isValid();
//@} //@}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -209,6 +212,9 @@ private:
//! Frame buffer supported //! Frame buffer supported
static bool m_IsFrameBufferSupported; static bool m_IsFrameBufferSupported;
//! State valid flag
static bool m_IsValid;
}; };
#endif /*GLC_STATE_H_*/ #endif /*GLC_STATE_H_*/

View File

@ -0,0 +1,101 @@
/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)
http://glc-lib.sourceforge.net
GLC-lib is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
GLC-lib is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_uniformshaderdata.cpp implementation of the GLC_UniformShaderData class.
#include <QtDebug>
#include "shading/glc_shader.h"
#include "glc_context.h"
#include "glc_uniformshaderdata.h"
GLC_UniformShaderData::GLC_UniformShaderData()
{
}
GLC_UniformShaderData::~GLC_UniformShaderData()
{
}
//////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////
void GLC_UniformShaderData::setLightValues(const GLC_Light& light)
{
}
void GLC_UniformShaderData::setLightingState(bool enable)
{
GLC_Shader* pCurrentShader= GLC_Shader::currentShaderHandle();
pCurrentShader->programShaderHandle()->setUniformValue(pCurrentShader->enableLightingId(), enable);
}
void GLC_UniformShaderData::setModelViewProjectionMatrix(const GLC_Matrix4x4& modelView, const GLC_Matrix4x4& projection)
{
// Set model view matrix
const double* pMvmatrixData= modelView.getData();
GLfloat mvFloatMatrix[4][4];
GLfloat* pData= &(mvFloatMatrix[0][0]);
for (int i= 0; i < 16; ++i)
{
pData[i]= static_cast<GLfloat>(pMvmatrixData[i]);
}
// Set model view projection matrix
GLC_Matrix4x4 modelViewProjectionMatrix= projection * modelView;
const double* pMvpmatrixData= modelViewProjectionMatrix.getData();
GLfloat mvpFloatMatrix[4][4];
pData= &(mvpFloatMatrix[0][0]);
for (int i= 0; i < 16; ++i)
{
pData[i]= static_cast<GLfloat>(pMvpmatrixData[i]);
}
// Set the transpose of inv model view matrix (For normal computation)
GLC_Matrix4x4 invTransposeModelView= modelView.inverted();
invTransposeModelView.transpose();
GLfloat invTmdv[3][3];
{
const double* data= invTransposeModelView.getData();
invTmdv[0][0]= static_cast<GLfloat>(data[0]); invTmdv[1][0]= static_cast<GLfloat>(data[4]); invTmdv[2][0]= static_cast<GLfloat>(data[8]);
invTmdv[0][1]= static_cast<GLfloat>(data[1]); invTmdv[1][1]= static_cast<GLfloat>(data[5]); invTmdv[2][1]= static_cast<GLfloat>(data[9]);
invTmdv[0][2]= static_cast<GLfloat>(data[2]); invTmdv[1][2]= static_cast<GLfloat>(data[6]); invTmdv[2][2]= static_cast<GLfloat>(data[10]);
}
Q_ASSERT(GLC_Shader::hasActiveShader());
GLC_Shader* pCurrentShader= GLC_Shader::currentShaderHandle();
pCurrentShader->programShaderHandle()->setUniformValue(pCurrentShader->modelViewLocationId(), mvFloatMatrix);
pCurrentShader->programShaderHandle()->setUniformValue(pCurrentShader->mvpLocationId(), mvpFloatMatrix);
pCurrentShader->programShaderHandle()->setUniformValue(pCurrentShader->invModelViewLocationId(), invTmdv);
}
void GLC_UniformShaderData::updateAll(const GLC_Context* pContext)
{
setModelViewProjectionMatrix(pContext->modelViewMatrix(), pContext->projectionMatrix());
setLightingState(pContext->lightingIsEnable());
}

View File

@ -0,0 +1,68 @@
/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)
http://glc-lib.sourceforge.net
GLC-lib is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
GLC-lib is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_uniformshaderdata.h interface for the GLC_UniformShaderData class.
#ifndef GLC_UNIFORMSHADERDATA_H_
#define GLC_UNIFORMSHADERDATA_H_
#include <QtOpenGL>
#include "maths/glc_matrix4x4.h"
#include "shading/glc_light.h"
#include "glc_config.h"
class GLC_Context;
class GLC_LIB_EXPORT GLC_UniformShaderData
{
public:
GLC_UniformShaderData();
virtual ~GLC_UniformShaderData();
//////////////////////////////////////////////////////////////////////
/*! \name Set Functions*/
//@{
//////////////////////////////////////////////////////////////////////
public:
//! Set Light values from the given light
void setLightValues(const GLC_Light& light);
//! Set lighting enbale state
void setLightingState(bool enable);
//! Set the model view matrix
void setModelViewProjectionMatrix(const GLC_Matrix4x4& modelView, const GLC_Matrix4x4& projection);
//! Update all uniform variables
void updateAll(const GLC_Context* pContext);
//@}
//////////////////////////////////////////////////////////////////////
// private members
//////////////////////////////////////////////////////////////////////
private:
};
#endif /* GLC_UNIFORMSHADERDATA_H_ */

View File

@ -0,0 +1,77 @@
/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)
http://glc-lib.sourceforge.net
GLC-lib is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
GLC-lib is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_glu.h declaration of glu functions
/*
* SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008)
* Copyright (C) 1991-2000 Silicon Graphics, Inc. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice including the dates of first publication and
* either this permission notice or a reference to
* http://oss.sgi.com/projects/FreeB/
* shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* SILICON GRAPHICS, INC. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
* OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Except as contained in this notice, the name of Silicon Graphics, Inc.
* shall not be used in advertising or otherwise to promote the sale, use or
* other dealings in this Software without prior written authorization from
* Silicon Graphics, Inc.
*/
#ifndef GLC_GLU_H_
#define GLC_GLU_H_
#include <QtOpenGL>
#include "../glc_config.h"
namespace glc
{
GLC_LIB_EXPORT void gluLookAt (GLdouble eyeX, GLdouble eyeY, GLdouble eyeZ, GLdouble centerX, GLdouble centerY, GLdouble centerZ, GLdouble upX, GLdouble upY, GLdouble upZ);
GLC_LIB_EXPORT void gluOrtho2D (GLdouble left, GLdouble right, GLdouble bottom, GLdouble top);
GLC_LIB_EXPORT void gluPerspective (GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar);
GLC_LIB_EXPORT void gluPickMatrix (GLdouble x, GLdouble y, GLdouble delX, GLdouble delY, GLint *viewport);
GLC_LIB_EXPORT GLint gluProject (GLdouble objX, GLdouble objY, GLdouble objZ, const GLdouble *model, const GLdouble *proj, const GLint *view, GLdouble* winX, GLdouble* winY, GLdouble* winZ);
GLC_LIB_EXPORT GLint gluUnProject (GLdouble winX, GLdouble winY, GLdouble winZ, const GLdouble *model, const GLdouble *proj, const GLint *view, GLdouble* objX, GLdouble* objY, GLdouble* objZ);
GLC_LIB_EXPORT GLint gluUnProject4 (GLdouble winX, GLdouble winY, GLdouble winZ, GLdouble clipW, const GLdouble *model, const GLdouble *proj, const GLint *view, GLdouble nearVal, GLdouble farVal, GLdouble* objX, GLdouble* objY, GLdouble* objZ, GLdouble* objW);
};
#endif /*GLC_GLU_H_*/

View File

@ -0,0 +1,379 @@
/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)
http://glc-lib.sourceforge.net
GLC-lib is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
GLC-lib is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_project implementation of glu project function
/*
* SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008)
* Copyright (C) 1991-2000 Silicon Graphics, Inc. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice including the dates of first publication and
* either this permission notice or a reference to
* http://oss.sgi.com/projects/FreeB/
* shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* SILICON GRAPHICS, INC. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
* OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Except as contained in this notice, the name of Silicon Graphics, Inc.
* shall not be used in advertising or otherwise to promote the sale, use or
* other dealings in this Software without prior written authorization from
* Silicon Graphics, Inc.
*/
#include "../glc_context.h"
#include "glc_glu.h"
/*
** Make m an identity matrix
*/
static void __gluMakeIdentityd(GLdouble m[16])
{
m[0+4*0] = 1; m[0+4*1] = 0; m[0+4*2] = 0; m[0+4*3] = 0;
m[1+4*0] = 0; m[1+4*1] = 1; m[1+4*2] = 0; m[1+4*3] = 0;
m[2+4*0] = 0; m[2+4*1] = 0; m[2+4*2] = 1; m[2+4*3] = 0;
m[3+4*0] = 0; m[3+4*1] = 0; m[3+4*2] = 0; m[3+4*3] = 1;
}
static void __gluMakeIdentityf(GLfloat m[16])
{
m[0+4*0] = 1; m[0+4*1] = 0; m[0+4*2] = 0; m[0+4*3] = 0;
m[1+4*0] = 0; m[1+4*1] = 1; m[1+4*2] = 0; m[1+4*3] = 0;
m[2+4*0] = 0; m[2+4*1] = 0; m[2+4*2] = 1; m[2+4*3] = 0;
m[3+4*0] = 0; m[3+4*1] = 0; m[3+4*2] = 0; m[3+4*3] = 1;
}
void glc::gluOrtho2D(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top)
{
GLC_Context::current()->glcOrtho(left, right, bottom, top, -1, 1);
}
#define __glPi 3.14159265358979323846
void glc::gluPerspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar)
{
GLdouble m[4][4];
double sine, cotangent, deltaZ;
double radians = fovy / 2 * __glPi / 180;
deltaZ = zFar - zNear;
sine = sin(radians);
if ((deltaZ == 0) || (sine == 0) || (aspect == 0)) {
return;
}
cotangent = cos(radians) / sine;
__gluMakeIdentityd(&m[0][0]);
m[0][0] = cotangent / aspect;
m[1][1] = cotangent;
m[2][2] = -(zFar + zNear) / deltaZ;
m[2][3] = -1;
m[3][2] = -2 * zNear * zFar / deltaZ;
m[3][3] = 0;
GLC_Context::current()->glcMultMatrix(GLC_Matrix4x4(&m[0][0]));
}
static void normalize(float v[3])
{
float r;
r = sqrt( v[0]*v[0] + v[1]*v[1] + v[2]*v[2] );
if (r == 0.0) return;
v[0] /= r;
v[1] /= r;
v[2] /= r;
}
static void cross(float v1[3], float v2[3], float result[3])
{
result[0] = v1[1]*v2[2] - v1[2]*v2[1];
result[1] = v1[2]*v2[0] - v1[0]*v2[2];
result[2] = v1[0]*v2[1] - v1[1]*v2[0];
}
void glc::gluLookAt(GLdouble eyex, GLdouble eyey, GLdouble eyez, GLdouble centerx,
GLdouble centery, GLdouble centerz, GLdouble upx, GLdouble upy,
GLdouble upz)
{
float forward[3], side[3], up[3];
GLfloat m[4][4];
forward[0] = centerx - eyex;
forward[1] = centery - eyey;
forward[2] = centerz - eyez;
up[0] = upx;
up[1] = upy;
up[2] = upz;
normalize(forward);
/* Side = forward x up */
cross(forward, up, side);
normalize(side);
/* Recompute up as: up = side x forward */
cross(side, forward, up);
__gluMakeIdentityf(&m[0][0]);
m[0][0] = side[0];
m[1][0] = side[1];
m[2][0] = side[2];
m[0][1] = up[0];
m[1][1] = up[1];
m[2][1] = up[2];
m[0][2] = -forward[0];
m[1][2] = -forward[1];
m[2][2] = -forward[2];
GLC_Matrix4x4 translate;
translate.setMatTranslate(-eyex, -eyey, -eyez);
GLC_Matrix4x4 result= GLC_Matrix4x4(&m[0][0]) * translate;
GLC_Context::current()->glcMultMatrix(result);
}
static void __gluMultMatrixVecd(const GLdouble matrix[16], const GLdouble in[4],
GLdouble out[4])
{
int i;
for (i=0; i<4; i++) {
out[i] =
in[0] * matrix[0*4+i] +
in[1] * matrix[1*4+i] +
in[2] * matrix[2*4+i] +
in[3] * matrix[3*4+i];
}
}
/*
** Invert 4x4 matrix.
** Contributed by David Moore (See Mesa bug #6748)
*/
static int __gluInvertMatrixd(const GLdouble m[16], GLdouble invOut[16])
{
double inv[16], det;
int i;
inv[0] = m[5]*m[10]*m[15] - m[5]*m[11]*m[14] - m[9]*m[6]*m[15]
+ m[9]*m[7]*m[14] + m[13]*m[6]*m[11] - m[13]*m[7]*m[10];
inv[4] = -m[4]*m[10]*m[15] + m[4]*m[11]*m[14] + m[8]*m[6]*m[15]
- m[8]*m[7]*m[14] - m[12]*m[6]*m[11] + m[12]*m[7]*m[10];
inv[8] = m[4]*m[9]*m[15] - m[4]*m[11]*m[13] - m[8]*m[5]*m[15]
+ m[8]*m[7]*m[13] + m[12]*m[5]*m[11] - m[12]*m[7]*m[9];
inv[12] = -m[4]*m[9]*m[14] + m[4]*m[10]*m[13] + m[8]*m[5]*m[14]
- m[8]*m[6]*m[13] - m[12]*m[5]*m[10] + m[12]*m[6]*m[9];
inv[1] = -m[1]*m[10]*m[15] + m[1]*m[11]*m[14] + m[9]*m[2]*m[15]
- m[9]*m[3]*m[14] - m[13]*m[2]*m[11] + m[13]*m[3]*m[10];
inv[5] = m[0]*m[10]*m[15] - m[0]*m[11]*m[14] - m[8]*m[2]*m[15]
+ m[8]*m[3]*m[14] + m[12]*m[2]*m[11] - m[12]*m[3]*m[10];
inv[9] = -m[0]*m[9]*m[15] + m[0]*m[11]*m[13] + m[8]*m[1]*m[15]
- m[8]*m[3]*m[13] - m[12]*m[1]*m[11] + m[12]*m[3]*m[9];
inv[13] = m[0]*m[9]*m[14] - m[0]*m[10]*m[13] - m[8]*m[1]*m[14]
+ m[8]*m[2]*m[13] + m[12]*m[1]*m[10] - m[12]*m[2]*m[9];
inv[2] = m[1]*m[6]*m[15] - m[1]*m[7]*m[14] - m[5]*m[2]*m[15]
+ m[5]*m[3]*m[14] + m[13]*m[2]*m[7] - m[13]*m[3]*m[6];
inv[6] = -m[0]*m[6]*m[15] + m[0]*m[7]*m[14] + m[4]*m[2]*m[15]
- m[4]*m[3]*m[14] - m[12]*m[2]*m[7] + m[12]*m[3]*m[6];
inv[10] = m[0]*m[5]*m[15] - m[0]*m[7]*m[13] - m[4]*m[1]*m[15]
+ m[4]*m[3]*m[13] + m[12]*m[1]*m[7] - m[12]*m[3]*m[5];
inv[14] = -m[0]*m[5]*m[14] + m[0]*m[6]*m[13] + m[4]*m[1]*m[14]
- m[4]*m[2]*m[13] - m[12]*m[1]*m[6] + m[12]*m[2]*m[5];
inv[3] = -m[1]*m[6]*m[11] + m[1]*m[7]*m[10] + m[5]*m[2]*m[11]
- m[5]*m[3]*m[10] - m[9]*m[2]*m[7] + m[9]*m[3]*m[6];
inv[7] = m[0]*m[6]*m[11] - m[0]*m[7]*m[10] - m[4]*m[2]*m[11]
+ m[4]*m[3]*m[10] + m[8]*m[2]*m[7] - m[8]*m[3]*m[6];
inv[11] = -m[0]*m[5]*m[11] + m[0]*m[7]*m[9] + m[4]*m[1]*m[11]
- m[4]*m[3]*m[9] - m[8]*m[1]*m[7] + m[8]*m[3]*m[5];
inv[15] = m[0]*m[5]*m[10] - m[0]*m[6]*m[9] - m[4]*m[1]*m[10]
+ m[4]*m[2]*m[9] + m[8]*m[1]*m[6] - m[8]*m[2]*m[5];
det = m[0]*inv[0] + m[1]*inv[4] + m[2]*inv[8] + m[3]*inv[12];
if (det == 0)
return GL_FALSE;
det = 1.0 / det;
for (i = 0; i < 16; i++)
invOut[i] = inv[i] * det;
return GL_TRUE;
}
static void __gluMultMatricesd(const GLdouble a[16], const GLdouble b[16],
GLdouble r[16])
{
int i, j;
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
r[i*4+j] =
a[i*4+0]*b[0*4+j] +
a[i*4+1]*b[1*4+j] +
a[i*4+2]*b[2*4+j] +
a[i*4+3]*b[3*4+j];
}
}
}
GLint glc::gluProject(GLdouble objx, GLdouble objy, GLdouble objz,
const GLdouble modelMatrix[16],
const GLdouble projMatrix[16],
const GLint viewport[4],
GLdouble *winx, GLdouble *winy, GLdouble *winz)
{
double in[4];
double out[4];
in[0]=objx;
in[1]=objy;
in[2]=objz;
in[3]=1.0;
__gluMultMatrixVecd(modelMatrix, in, out);
__gluMultMatrixVecd(projMatrix, out, in);
if (in[3] == 0.0) return(GL_FALSE);
in[0] /= in[3];
in[1] /= in[3];
in[2] /= in[3];
/* Map x, y and z to range 0-1 */
in[0] = in[0] * 0.5 + 0.5;
in[1] = in[1] * 0.5 + 0.5;
in[2] = in[2] * 0.5 + 0.5;
/* Map x,y to viewport */
in[0] = in[0] * viewport[2] + viewport[0];
in[1] = in[1] * viewport[3] + viewport[1];
*winx=in[0];
*winy=in[1];
*winz=in[2];
return(GL_TRUE);
}
GLint glc::gluUnProject(GLdouble winx, GLdouble winy, GLdouble winz,
const GLdouble modelMatrix[16],
const GLdouble projMatrix[16],
const GLint viewport[4],
GLdouble *objx, GLdouble *objy, GLdouble *objz)
{
double finalMatrix[16];
double in[4];
double out[4];
__gluMultMatricesd(modelMatrix, projMatrix, finalMatrix);
if (!__gluInvertMatrixd(finalMatrix, finalMatrix)) return(GL_FALSE);
in[0]=winx;
in[1]=winy;
in[2]=winz;
in[3]=1.0;
/* Map x and y from window coordinates */
in[0] = (in[0] - viewport[0]) / viewport[2];
in[1] = (in[1] - viewport[1]) / viewport[3];
/* Map to range -1 to 1 */
in[0] = in[0] * 2 - 1;
in[1] = in[1] * 2 - 1;
in[2] = in[2] * 2 - 1;
__gluMultMatrixVecd(finalMatrix, in, out);
if (out[3] == 0.0) return(GL_FALSE);
out[0] /= out[3];
out[1] /= out[3];
out[2] /= out[3];
*objx = out[0];
*objy = out[1];
*objz = out[2];
return(GL_TRUE);
}
GLint glc::gluUnProject4(GLdouble winx, GLdouble winy, GLdouble winz, GLdouble clipw,
const GLdouble modelMatrix[16],
const GLdouble projMatrix[16],
const GLint viewport[4],
GLclampd nearVal, GLclampd farVal,
GLdouble *objx, GLdouble *objy, GLdouble *objz,
GLdouble *objw)
{
double finalMatrix[16];
double in[4];
double out[4];
__gluMultMatricesd(modelMatrix, projMatrix, finalMatrix);
if (!__gluInvertMatrixd(finalMatrix, finalMatrix)) return(GL_FALSE);
in[0]=winx;
in[1]=winy;
in[2]=winz;
in[3]=clipw;
/* Map x and y from window coordinates */
in[0] = (in[0] - viewport[0]) / viewport[2];
in[1] = (in[1] - viewport[1]) / viewport[3];
in[2] = (in[2] - nearVal) / (farVal - nearVal);
/* Map to range -1 to 1 */
in[0] = in[0] * 2 - 1;
in[1] = in[1] * 2 - 1;
in[2] = in[2] * 2 - 1;
__gluMultMatrixVecd(finalMatrix, in, out);
if (out[3] == 0.0) return(GL_FALSE);
*objx = out[0];
*objy = out[1];
*objz = out[2];
*objw = out[3];
return(GL_TRUE);
}
void glc::gluPickMatrix(GLdouble x, GLdouble y, GLdouble deltax, GLdouble deltay,
GLint viewport[4])
{
if (deltax <= 0 || deltay <= 0) {
return;
}
/* Translate and scale the picked region to the entire window */
GLC_Matrix4x4 translate;
translate.setMatTranslate((viewport[2] - 2 * (x - viewport[0])) / deltax, (viewport[3] - 2 * (y - viewport[1])) / deltay, 0.0);
GLC_Matrix4x4 scaling;
scaling.setMatScaling(viewport[2] / deltax, viewport[3] / deltay, 0.0);
GLC_Context::current()->glcMultMatrix(translate * scaling);
}

View File

@ -0,0 +1 @@
#include "glc_context.h"

View File

@ -0,0 +1 @@
#include "glc_contextmanager.h"

View File

@ -0,0 +1 @@
#include "glu/glc_glu.h"

View File

@ -1 +1 @@
#include <sceneGraph/glc_octree.h> #include "sceneGraph/glc_octree.h"

View File

@ -1 +1 @@
#include <sceneGraph/glc_octreenode.h> #include "sceneGraph/glc_octreenode.h"

View File

@ -1 +0,0 @@
#include "glc_openglstate.h

View File

@ -0,0 +1 @@
#include "glc_renderstate.h

View File

@ -1 +1 @@
#include <sceneGraph/glc_spacepertitionning.h> #include "sceneGraph/glc_spacepertitionning.h"

View File

@ -1 +1 @@
#include <sceneGraph/glc_structinstance.h> #include "sceneGraph/glc_structinstance.h"

View File

@ -1 +1 @@
#include <sceneGraph/glc_structoccurence.h> #include "sceneGraph/glc_structoccurence.h"

View File

@ -1 +1 @@
#include <sceneGraph/glc_structreference.h> #include "sceneGraph/glc_structreference.h"

View File

@ -0,0 +1 @@
#include "viewport/tsrmover.h"

View File

@ -0,0 +1 @@
#include "viewport/glc_userinput.h"

View File

@ -45,10 +45,9 @@
#include <QFileInfo> #include <QFileInfo>
#include <QGLContext> #include <QGLContext>
GLC_3dsToWorld::GLC_3dsToWorld(const QGLContext *pContext) GLC_3dsToWorld::GLC_3dsToWorld()
: m_pWorld(NULL) : m_pWorld(NULL)
, m_FileName() , m_FileName()
, m_pQGLContext(pContext)
, m_pCurrentMesh(NULL) , m_pCurrentMesh(NULL)
, m_pLib3dsFile(NULL) , m_pLib3dsFile(NULL)
, m_Materials() , m_Materials()
@ -387,7 +386,7 @@ void GLC_3dsToWorld::loadMaterial(Lib3dsMaterial* p3dsMaterial)
if (textureFile.open(QIODevice::ReadOnly)) if (textureFile.open(QIODevice::ReadOnly))
{ {
// Create the texture and assign it to the material // Create the texture and assign it to the material
GLC_Texture *pTexture = new GLC_Texture(m_pQGLContext, textureFile); GLC_Texture *pTexture = new GLC_Texture(textureFile);
pMaterial->setTexture(pTexture); pMaterial->setTexture(pTexture);
m_ListOfAttachedFileName << textureFileName; m_ListOfAttachedFileName << textureFileName;
textureFile.close(); textureFile.close();

View File

@ -72,7 +72,7 @@ class GLC_LIB_EXPORT GLC_3dsToWorld : public QObject
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
public: public:
GLC_3dsToWorld(const QGLContext*); GLC_3dsToWorld();
virtual ~GLC_3dsToWorld(); virtual ~GLC_3dsToWorld();
//@} //@}
@ -125,9 +125,6 @@ private:
//! The 3DS File name //! The 3DS File name
QString m_FileName; QString m_FileName;
//! OpenGL Context
const QGLContext* m_pQGLContext;
//! The current mesh //! The current mesh
GLC_Mesh* m_pCurrentMesh; GLC_Mesh* m_pCurrentMesh;

View File

@ -45,9 +45,8 @@ QMutex GLC_3dxmlToWorld::m_ZipMutex;
static qint64 chunckSize= 10000000; static qint64 chunckSize= 10000000;
GLC_3dxmlToWorld::GLC_3dxmlToWorld(const QGLContext* pContext) GLC_3dxmlToWorld::GLC_3dxmlToWorld()
: QObject() : QObject()
, m_pQGLContext(pContext)
, m_pStreamReader(NULL) , m_pStreamReader(NULL)
, m_FileName() , m_FileName()
, m_p3dxmlArchive(NULL) , m_p3dxmlArchive(NULL)
@ -72,9 +71,11 @@ GLC_3dxmlToWorld::GLC_3dxmlToWorld(const QGLContext* pContext)
, m_SetOfAttachedFileName() , m_SetOfAttachedFileName()
, m_CurrentFileName() , m_CurrentFileName()
, m_CurrentDateTime() , m_CurrentDateTime()
, m_OccurenceAttrib() , m_V3OccurenceAttribHash()
, m_V4OccurenceAttribList()
, m_GetExternalRef3DName(false) , m_GetExternalRef3DName(false)
, m_ByteArrayList() , m_ByteArrayList()
, m_IsVersion3(false)
{ {
} }
@ -90,13 +91,18 @@ GLC_3dxmlToWorld::~GLC_3dxmlToWorld()
clearMaterialHash(); clearMaterialHash();
// Clear specific attributes hash table // Clear specific attributes hash table
QHash<unsigned int, OccurenceAttrib*>::iterator iAttrib= m_OccurenceAttrib.begin(); QHash<unsigned int, V3OccurenceAttrib*>::iterator iAttrib= m_V3OccurenceAttribHash.begin();
while (m_OccurenceAttrib.constEnd() != iAttrib) while (m_V3OccurenceAttribHash.constEnd() != iAttrib)
{ {
delete iAttrib.value(); delete iAttrib.value();
++iAttrib; ++iAttrib;
} }
m_OccurenceAttrib.clear();
const int v4OccurenceAttribCount= m_V4OccurenceAttribList.count();
for (int i= 0; i < v4OccurenceAttribCount; ++i)
{
delete m_V4OccurenceAttribList.at(i);
}
} }
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -144,6 +150,9 @@ GLC_World* GLC_3dxmlToWorld::createWorldFrom3dxml(QFile &file, bool structureOnl
loadCatMaterialRef(); loadCatMaterialRef();
} }
// Read the header
readHeader();
// Load the product structure // Load the product structure
loadProductStructure(); loadProductStructure();
@ -179,7 +188,7 @@ GLC_3DRep GLC_3dxmlToWorld::create3DrepFrom3dxmlRep(const QString& fileName)
m_CurrentFileName= glc::archiveEntryFileName(fileName); m_CurrentFileName= glc::archiveEntryFileName(fileName);
// Get the 3DXML time stamp // Get the 3DXML time stamp
m_CurrentDateTime= QFileInfo(QFileInfo(m_FileName).absolutePath() + QDir::separator() + QFileInfo(fileName).fileName()).lastModified(); m_CurrentDateTime= QFileInfo(QFileInfo(m_FileName)).lastModified();
} }
else if (glc::isFileString(fileName)) else if (glc::isFileString(fileName))
{ {
@ -231,7 +240,7 @@ GLC_3DRep GLC_3dxmlToWorld::create3DrepFrom3dxmlRep(const QString& fileName)
} }
} }
} }
else if (QFileInfo(m_CurrentFileName).suffix().toLower() == "3drep") else if ((QFileInfo(m_CurrentFileName).suffix().toLower() == "3drep") || (QFileInfo(m_CurrentFileName).suffix().toLower() == "xml"))
{ {
if (GLC_State::cacheIsUsed() && GLC_State::currentCacheManager().isUsable(m_CurrentDateTime, QFileInfo(m_FileName).baseName(), QFileInfo(m_CurrentFileName).fileName())) if (GLC_State::cacheIsUsed() && GLC_State::currentCacheManager().isUsable(m_CurrentDateTime, QFileInfo(m_FileName).baseName(), QFileInfo(m_CurrentFileName).fileName()))
{ {
@ -310,7 +319,7 @@ void GLC_3dxmlToWorld::goToRepId(const QString& id)
while(!m_pStreamReader->atEnd() && !((QXmlStreamReader::StartElement == m_pStreamReader->tokenType()) && (m_pStreamReader->name() == "Representation") while(!m_pStreamReader->atEnd() && !((QXmlStreamReader::StartElement == m_pStreamReader->tokenType()) && (m_pStreamReader->name() == "Representation")
&& (m_pStreamReader->attributes().value("id").toString() == id))) && (m_pStreamReader->attributes().value("id").toString() == id)))
{ {
readNext();; readNext();
} }
} }
@ -324,7 +333,7 @@ void GLC_3dxmlToWorld::gotToPolygonalRepType()
{ {
//qDebug() << m_pStreamReader->name(); //qDebug() << m_pStreamReader->name();
//qDebug() << m_pStreamReader->attributes().value("xsi:type").toString(); //qDebug() << m_pStreamReader->attributes().value("xsi:type").toString();
readNext();; readNext();
} }
} }
@ -347,10 +356,34 @@ QString GLC_3dxmlToWorld::readAttribute(const QString& name, bool required)
return attributeValue; return attributeValue;
} }
void GLC_3dxmlToWorld::readHeader()
{
setStreamReaderToFile(m_RootName);
goToElement(m_pStreamReader, "Header");
if (m_pStreamReader->atEnd() || m_pStreamReader->hasError())
{
QString message(QString("GLC_3dxmlToWorld::readHeader Element Header Not found in ") + m_FileName);
GLC_FileFormatException fileFormatException(message, m_FileName, GLC_FileFormatException::WrongFileFormat);
clear();
throw(fileFormatException);
}
while(endElementNotReached(m_pStreamReader, "Header"))
{
if ((QXmlStreamReader::StartElement == m_pStreamReader->tokenType()) && (m_pStreamReader->name() == "SchemaVersion"))
{
QString version= getContent(m_pStreamReader, "SchemaVersion");
m_IsVersion3= version.startsWith('3');
}
readNext();
}
}
// Load the product structure // Load the product structure
void GLC_3dxmlToWorld::loadProductStructure() void GLC_3dxmlToWorld::loadProductStructure()
{ {
setStreamReaderToFile(m_RootName);
goToElement(m_pStreamReader, "ProductStructure"); goToElement(m_pStreamReader, "ProductStructure");
if (m_pStreamReader->atEnd() || m_pStreamReader->hasError()) if (m_pStreamReader->atEnd() || m_pStreamReader->hasError())
{ {
@ -373,7 +406,7 @@ void GLC_3dxmlToWorld::loadProductStructure()
else loadInstanceRep(); else loadInstanceRep();
} }
readNext();; readNext();
} }
// Load Default view properties // Load Default view properties
@ -382,11 +415,11 @@ void GLC_3dxmlToWorld::loadProductStructure()
if ((QXmlStreamReader::StartElement == m_pStreamReader->tokenType()) if ((QXmlStreamReader::StartElement == m_pStreamReader->tokenType())
&& ((m_pStreamReader->name() == "DefaultView") || (m_pStreamReader->name() == "GeometricRepresentationSet"))) && ((m_pStreamReader->name() == "DefaultView") || (m_pStreamReader->name() == "GeometricRepresentationSet")))
{ {
if (m_pStreamReader->name() == "DefaultView") loadGraphicsProperties(); if (m_pStreamReader->name() == "DefaultView") loadDefaultView();
else if (m_pStreamReader->name() == "GeometricRepresentationSet") loadLocalRepresentations(); else if (m_pStreamReader->name() == "GeometricRepresentationSet") loadLocalRepresentations();
} }
readNext();; readNext();
} }
// Check if an error Occur // Check if an error Occur
@ -478,17 +511,17 @@ void GLC_3dxmlToWorld::loadProductStructure()
// Update occurence number // Update occurence number
m_pWorld->rootOccurence()->updateOccurenceNumber(1); m_pWorld->rootOccurence()->updateOccurenceNumber(1);
// Change occurence attributes // Change occurence attributes for 3DXML V3
if (! m_OccurenceAttrib.isEmpty()) if (! m_V3OccurenceAttribHash.isEmpty())
{ {
//qDebug() << "Not visible occurence= " << m_OccurenceAttrib.size(); //qDebug() << "Not visible occurence= " << m_V3OccurenceAttribHash.size();
QList<GLC_StructOccurence*> occurenceList= m_pWorld->listOfOccurence(); QList<GLC_StructOccurence*> occurenceList= m_pWorld->listOfOccurence();
const int size= occurenceList.size(); const int size= occurenceList.size();
for (int i= 0; i < size; ++i) for (int i= 0; i < size; ++i)
{ {
if (m_OccurenceAttrib.contains(occurenceList.at(i)->occurenceNumber())) if (m_V3OccurenceAttribHash.contains(occurenceList.at(i)->occurenceNumber()))
{ {
OccurenceAttrib* pOccurenceAttrib= m_OccurenceAttrib.value(occurenceList.at(i)->occurenceNumber()); V3OccurenceAttrib* pOccurenceAttrib= m_V3OccurenceAttribHash.value(occurenceList.at(i)->occurenceNumber());
occurenceList.at(i)->setVisibility(pOccurenceAttrib->m_IsVisible); occurenceList.at(i)->setVisibility(pOccurenceAttrib->m_IsVisible);
if (NULL != pOccurenceAttrib->m_pRenderProperties) if (NULL != pOccurenceAttrib->m_pRenderProperties)
{ {
@ -497,6 +530,27 @@ void GLC_3dxmlToWorld::loadProductStructure()
} }
} }
} }
// Change occurence attributes for 3DXML V4
if (!m_V4OccurenceAttribList.isEmpty())
{
QHash<GLC_StructInstance*, unsigned int> instanceToIdHash;
const int assyCount= m_AssyLinkList.count();
for (int i= 0; i < assyCount; ++i)
{
AssyLink assyLink= m_AssyLinkList.at(i);
instanceToIdHash.insert(assyLink.m_pChildInstance, assyLink.m_InstanceId);
}
const int attribCount= m_V4OccurenceAttribList.count();
for (int i= 0; i < attribCount; ++i)
{
V4OccurenceAttrib* pCurrentV4OccurenceAttrib= m_V4OccurenceAttribList.at(i);
//qDebug() << pCurrentV4OccurenceAttrib->m_Path;
applyV4Attribute(m_pWorld->rootOccurence(), pCurrentV4OccurenceAttrib, instanceToIdHash);
}
}
// Check usage of Instance // Check usage of Instance
InstanceOfExtRefHash::const_iterator iInstance= m_InstanceOfExtRefHash.constBegin(); InstanceOfExtRefHash::const_iterator iInstance= m_InstanceOfExtRefHash.constBegin();
while (m_InstanceOfExtRefHash.constEnd() != iInstance) while (m_InstanceOfExtRefHash.constEnd() != iInstance)
@ -570,10 +624,10 @@ void GLC_3dxmlToWorld::loadReference3D()
} }
userAttributes.insert(name, value); userAttributes.insert(name, value);
} }
readNext();; readNext();
} }
} }
readNext();; readNext();
} }
if (!userAttributes.isEmpty()) if (!userAttributes.isEmpty())
{ {
@ -591,6 +645,7 @@ void GLC_3dxmlToWorld::loadInstance3D()
const unsigned int instanceId= readAttribute("id", true).toUInt(); const unsigned int instanceId= readAttribute("id", true).toUInt();
const QString instName(readAttribute("name", false)); const QString instName(readAttribute("name", false));
goToElement(m_pStreamReader, "IsAggregatedBy");
const unsigned int aggregatedById= getContent(m_pStreamReader, "IsAggregatedBy").toUInt(); const unsigned int aggregatedById= getContent(m_pStreamReader, "IsAggregatedBy").toUInt();
QString instanceOf= getContent(m_pStreamReader, "IsInstanceOf"); QString instanceOf= getContent(m_pStreamReader, "IsInstanceOf");
const QString matrixString= getContent(m_pStreamReader, "RelativeMatrix"); const QString matrixString= getContent(m_pStreamReader, "RelativeMatrix");
@ -614,10 +669,10 @@ void GLC_3dxmlToWorld::loadInstance3D()
QString value= readAttribute("value", true); QString value= readAttribute("value", true);
userAttributes.insert(name, value); userAttributes.insert(name, value);
} }
readNext();; readNext();
} }
} }
readNext();; readNext();
} }
if (!userAttributes.isEmpty()) if (!userAttributes.isEmpty())
{ {
@ -687,7 +742,7 @@ void GLC_3dxmlToWorld::loadInstanceRep()
{ {
const QString local= "urn:3DXML:Reference:loc:"; const QString local= "urn:3DXML:Reference:loc:";
//const QString instName(readAttribute("name", true)); goToElement(m_pStreamReader, "IsAggregatedBy");
const unsigned int aggregatedById= getContent(m_pStreamReader, "IsAggregatedBy").toUInt(); const unsigned int aggregatedById= getContent(m_pStreamReader, "IsAggregatedBy").toUInt();
QString instanceOf= getContent(m_pStreamReader, "IsInstanceOf"); QString instanceOf= getContent(m_pStreamReader, "IsInstanceOf");
@ -745,7 +800,6 @@ void GLC_3dxmlToWorld::loadExternalRef3D()
GLC_3DRep* pRep= new GLC_3DRep(binaryRep.loadRep()); GLC_3DRep* pRep= new GLC_3DRep(binaryRep.loadRep());
setRepresentationFileName(pRep); setRepresentationFileName(pRep);
factorizeMaterial(pRep);
GLC_StructReference* pCurrentRef= new GLC_StructReference(pRep); GLC_StructReference* pCurrentRef= new GLC_StructReference(pRep);
pCurrentRef->setName(QFileInfo(m_CurrentFileName).baseName()); pCurrentRef->setName(QFileInfo(m_CurrentFileName).baseName());
@ -952,103 +1006,7 @@ GLC_StructReference* GLC_3dxmlToWorld::createReferenceRep(QString repId, GLC_3DR
currentMesh3DRep.addGeom(pMesh); currentMesh3DRep.addGeom(pMesh);
} }
// Get the master lod accuracy loadRep(pMesh);
double masterLodAccuracy= readAttribute("accuracy", false).toDouble();
loadLOD(pMesh);
if (m_pStreamReader->atEnd() || m_pStreamReader->hasError())
{
QStringList stringList(m_FileName);
stringList.append(m_CurrentFileName);
stringList.append("Master LOD not found");
GLC_ErrorLog::addError(stringList);
return new GLC_StructReference("Empty Rep");
}
// Load Faces index data
while (endElementNotReached(m_pStreamReader, "Faces"))
{
readNext();;
if ( m_pStreamReader->name() == "Face")
{
loadFace(pMesh, 0, masterLodAccuracy);
}
}
checkForXmlError("End of Faces not found");
while (startElementNotReached(m_pStreamReader, "Edges") && startElementNotReached(m_pStreamReader, "VertexBuffer"))
{
readNext();;
}
checkForXmlError("Element VertexBuffer not found");
if (m_pStreamReader->name() == "Edges")
{
while (endElementNotReached(m_pStreamReader, "Edges"))
{
readNext();;
if ( m_pStreamReader->name() == "Polyline")
{
loadPolyline(pMesh);
readNext();;
}
}
}
{
QString verticePosition= getContent(m_pStreamReader, "Positions").replace(',', ' ');
//qDebug() << "Position " << verticePosition;
checkForXmlError("Error while retrieving Position ContentVertexBuffer");
// Load Vertice position
QTextStream verticeStream(&verticePosition);
QList<GLfloat> verticeValues;
QString buff;
while ((!verticeStream.atEnd()))
{
verticeStream >> buff;
verticeValues.append(buff.toFloat());
}
pMesh->addVertice(verticeValues.toVector());
}
{
QString normals= getContent(m_pStreamReader, "Normals").replace(',', ' ');
//qDebug() << "Normals " << normals;
checkForXmlError("Error while retrieving Normals values");
// Load Vertice Normals
QTextStream normalsStream(&normals);
QList<GLfloat> normalValues;
QString buff;
while ((!normalsStream.atEnd()))
{
normalsStream >> buff;
normalValues.append(buff.toFloat());
}
pMesh->addNormals(normalValues.toVector());
}
// Try to find texture coordinate
while (endElementNotReached(m_pStreamReader, "VertexBuffer"))
{
//qDebug() << "Try to find texture coordinate " << m_pStreamReader->name() << " " << m_pStreamReader->lineNumber();
if ((QXmlStreamReader::StartElement == m_pStreamReader->tokenType()) && (m_pStreamReader->name() == "TextureCoordinates"))
{
QString texels= getContent(m_pStreamReader, "TextureCoordinates").replace(',', ' ');
checkForXmlError("Error while retrieving Texture coordinates");
QTextStream texelStream(&texels);
QList<GLfloat> texelValues;
QString buff;
while ((!texelStream.atEnd()))
{
texelStream >> buff;
texelValues.append(buff.toFloat());
}
pMesh->addTexels(texelValues.toVector());
}
readNext();;
}
++numberOfMesh; ++numberOfMesh;
} }
@ -1166,8 +1124,6 @@ void GLC_3dxmlToWorld::createUnfoldedTree()
++iLink; ++iLink;
} }
m_AssyLinkList.clear();
// Check the assembly structure occurence // Check the assembly structure occurence
ReferenceHash::const_iterator iRef= m_ReferenceHash.constBegin(); ReferenceHash::const_iterator iRef= m_ReferenceHash.constBegin();
while (m_ReferenceHash.constEnd() != iRef) while (m_ReferenceHash.constEnd() != iRef)
@ -1239,34 +1195,7 @@ void GLC_3dxmlToWorld::checkForXmlError(const QString& info)
throw(fileFormatException); throw(fileFormatException);
} }
} }
// Go to the master LOD
void GLC_3dxmlToWorld::loadLOD(GLC_Mesh* pMesh)
{
int lodIndex= 1;
while(!m_pStreamReader->atEnd() && !((QXmlStreamReader::StartElement == m_pStreamReader->tokenType()) && (m_pStreamReader->name() == "Faces")))
{
readNext();;
if ((QXmlStreamReader::StartElement == m_pStreamReader->tokenType()) && (m_pStreamReader->name() == "SurfaceAttributes"))
{
m_pCurrentMaterial= loadSurfaceAttributes();
}
else if ((QXmlStreamReader::StartElement == m_pStreamReader->tokenType()) && (m_pStreamReader->name() == "PolygonalLOD"))
{
double accuracy= readAttribute("accuracy", true).toDouble();
// Load Faces index data
while (endElementNotReached(m_pStreamReader, "Faces"))
{
readNext();;
if ( m_pStreamReader->name() == "Face")
{
loadFace(pMesh, lodIndex, accuracy);
}
}
checkForXmlError("End of Faces not found");
++lodIndex;
}
}
}
// Load a face // Load a face
void GLC_3dxmlToWorld::loadFace(GLC_Mesh* pMesh, const int lod, double accuracy) void GLC_3dxmlToWorld::loadFace(GLC_Mesh* pMesh, const int lod, double accuracy)
{ {
@ -1292,7 +1221,7 @@ void GLC_3dxmlToWorld::loadFace(GLC_Mesh* pMesh, const int lod, double accuracy)
{ {
pCurrentMaterial= loadSurfaceAttributes(); pCurrentMaterial= loadSurfaceAttributes();
} }
readNext();; readNext();
} }
if (NULL == pCurrentMaterial) if (NULL == pCurrentMaterial)
{ {
@ -1365,14 +1294,30 @@ void GLC_3dxmlToWorld::loadPolyline(GLC_Mesh* pMesh)
data.replace(',', ' '); data.replace(',', ' ');
QTextStream dataStream(&data); QTextStream dataStream(&data);
GLfloatVector dataVector; QList<GLfloat> values;
QString buff; QString buff;
while ((!dataStream.atEnd())) while ((!dataStream.atEnd()))
{ {
dataStream >> buff; dataStream >> buff;
dataVector.append(buff.toFloat()); values.append(buff.toFloat());
} }
pMesh->addVerticeGroup(dataVector); if ((values.size() % 3) == 0)
{
pMesh->addVerticeGroup(values.toVector());
}
else
{
QString message(QString("polyline buffer is not a multiple of 3 ") + m_CurrentFileName);
QStringList stringList(message);
GLC_ErrorLog::addError(stringList);
GLC_FileFormatException fileFormatException(message, m_FileName, GLC_FileFormatException::WrongFileFormat);
clear();
throw(fileFormatException);
}
} }
// Clear material hash // Clear material hash
@ -1404,7 +1349,7 @@ GLC_Material* GLC_3dxmlToWorld::loadSurfaceAttributes()
{ {
while (endElementNotReached(m_pStreamReader, "MaterialApplication")) while (endElementNotReached(m_pStreamReader, "MaterialApplication"))
{ {
readNext();; readNext();
if ((QXmlStreamReader::StartElement == m_pStreamReader->tokenType()) && (m_pStreamReader->name() == "MaterialId")) if ((QXmlStreamReader::StartElement == m_pStreamReader->tokenType()) && (m_pStreamReader->name() == "MaterialId"))
{ {
checkForXmlError("Material ID not found"); checkForXmlError("Material ID not found");
@ -1414,7 +1359,7 @@ GLC_Material* GLC_3dxmlToWorld::loadSurfaceAttributes()
} }
} }
readNext();; readNext();
} }
return pMaterial; return pMaterial;
@ -1566,7 +1511,7 @@ void GLC_3dxmlToWorld::loadLocalRepresentations()
} }
delete pRef; delete pRef;
} }
readNext();; readNext();
} }
//qDebug() << "Local rep loaded"; //qDebug() << "Local rep loaded";
@ -1586,7 +1531,7 @@ void GLC_3dxmlToWorld::loadLocalRepresentations()
} }
} }
void GLC_3dxmlToWorld::loadGraphicsProperties() void GLC_3dxmlToWorld::loadDefaultView()
{ {
if (m_pStreamReader->atEnd() || m_pStreamReader->hasError()) if (m_pStreamReader->atEnd() || m_pStreamReader->hasError())
{ {
@ -1601,10 +1546,11 @@ void GLC_3dxmlToWorld::loadGraphicsProperties()
{ {
if ((QXmlStreamReader::StartElement == m_pStreamReader->tokenType()) && (m_pStreamReader->name() == "DefaultViewProperty")) if ((QXmlStreamReader::StartElement == m_pStreamReader->tokenType()) && (m_pStreamReader->name() == "DefaultViewProperty"))
{ {
loadDefaultViewProperty(); if (m_IsVersion3) loadV3DefaultViewProperty();
else loadV4DefaultViewProperty();
} }
readNext();; readNext();
} }
// Check if an error Occur // Check if an error Occur
@ -1618,7 +1564,7 @@ void GLC_3dxmlToWorld::loadGraphicsProperties()
} }
void GLC_3dxmlToWorld::loadDefaultViewProperty() void GLC_3dxmlToWorld::loadV3DefaultViewProperty()
{ {
goToElement(m_pStreamReader, "OccurenceId"); goToElement(m_pStreamReader, "OccurenceId");
unsigned int occurenceId= getContent(m_pStreamReader, "OccurenceId").toUInt(); unsigned int occurenceId= getContent(m_pStreamReader, "OccurenceId").toUInt();
@ -1635,13 +1581,13 @@ void GLC_3dxmlToWorld::loadDefaultViewProperty()
QString visibleString= readAttribute("visible", true); QString visibleString= readAttribute("visible", true);
if (visibleString != "true") if (visibleString != "true")
{ {
if (!m_OccurenceAttrib.contains(occurenceId)) if (!m_V3OccurenceAttribHash.contains(occurenceId))
{ {
OccurenceAttrib* pOccurenceAttrib= new OccurenceAttrib(); V3OccurenceAttrib* pOccurenceAttrib= new V3OccurenceAttrib();
pOccurenceAttrib->m_IsVisible= false; pOccurenceAttrib->m_IsVisible= false;
m_OccurenceAttrib.insert(occurenceId, pOccurenceAttrib); m_V3OccurenceAttribHash.insert(occurenceId, pOccurenceAttrib);
} }
else m_OccurenceAttrib.value(occurenceId)->m_IsVisible= false; else m_V3OccurenceAttribHash.value(occurenceId)->m_IsVisible= false;
} }
} }
else if ((QXmlStreamReader::StartElement == m_pStreamReader->tokenType()) && (m_pStreamReader->name() == "SurfaceAttributes")) else if ((QXmlStreamReader::StartElement == m_pStreamReader->tokenType()) && (m_pStreamReader->name() == "SurfaceAttributes"))
@ -1669,21 +1615,21 @@ void GLC_3dxmlToWorld::loadDefaultViewProperty()
pRenderProperties->setOverwriteTransparency(static_cast<float>(alpha)); pRenderProperties->setOverwriteTransparency(static_cast<float>(alpha));
pRenderProperties->setRenderingMode(glc::OverwriteTransparency); pRenderProperties->setRenderingMode(glc::OverwriteTransparency);
} }
if (!m_OccurenceAttrib.contains(occurenceId)) if (!m_V3OccurenceAttribHash.contains(occurenceId))
{ {
OccurenceAttrib* pOccurenceAttrib= new OccurenceAttrib(); V3OccurenceAttrib* pOccurenceAttrib= new V3OccurenceAttrib();
pOccurenceAttrib->m_pRenderProperties= pRenderProperties; pOccurenceAttrib->m_pRenderProperties= pRenderProperties;
m_OccurenceAttrib.insert(occurenceId, pOccurenceAttrib); m_V3OccurenceAttribHash.insert(occurenceId, pOccurenceAttrib);
} }
else m_OccurenceAttrib.value(occurenceId)->m_pRenderProperties= pRenderProperties; else m_V3OccurenceAttribHash.value(occurenceId)->m_pRenderProperties= pRenderProperties;
} }
readNext();; readNext();
} }
} }
readNext();; readNext();
} }
// Check if an error Occur // Check if an error Occur
@ -1696,6 +1642,120 @@ void GLC_3dxmlToWorld::loadDefaultViewProperty()
} }
} }
void GLC_3dxmlToWorld::loadV4DefaultViewProperty()
{
V4OccurenceAttrib* pV4OccurenceAttrib= new V4OccurenceAttrib();
while(endElementNotReached(m_pStreamReader, "DefaultViewProperty"))
{
if ((QXmlStreamReader::StartElement == m_pStreamReader->tokenType()) && (m_pStreamReader->name() == "OccurenceId"))
{
pV4OccurenceAttrib->m_Path= loadOccurencePath();
}
else if ((QXmlStreamReader::StartElement == m_pStreamReader->tokenType()) && (m_pStreamReader->name() == "RelativePosition"))
{
const QString matrix= getContent(m_pStreamReader, "RelativePosition");
pV4OccurenceAttrib->m_pMatrix= new GLC_Matrix4x4(loadMatrix(matrix));
}
else if ((QXmlStreamReader::StartElement == m_pStreamReader->tokenType()) && (m_pStreamReader->name() == "GraphicProperties"))
{
loadGraphicProperties(pV4OccurenceAttrib);
}
readNext();
}
if(!pV4OccurenceAttrib->m_Path.isEmpty())
{
m_V4OccurenceAttribList.append(pV4OccurenceAttrib);
}
else
{
delete pV4OccurenceAttrib;
}
// Check if an error Occur
if (m_pStreamReader->hasError())
{
QString message(QString("GLC_3dxmlToWorld::loadV4DefaultViewProperty An error occur in ") + m_FileName);
GLC_FileFormatException fileFormatException(message, m_FileName, GLC_FileFormatException::WrongFileFormat);
clear();
throw(fileFormatException);
}
}
QList<unsigned int> GLC_3dxmlToWorld::loadOccurencePath()
{
QList<unsigned int> path;
while(endElementNotReached(m_pStreamReader, "OccurenceId"))
{
if ((QXmlStreamReader::StartElement == m_pStreamReader->tokenType()) && (m_pStreamReader->name() == "id"))
{
QString instanceId= getContent(m_pStreamReader, "id");
instanceId= instanceId.right(instanceId.length() - 1 - instanceId.indexOf('#'));
path.append(instanceId.toUInt());
}
readNext();
}
// Check if an error Occur
if (m_pStreamReader->hasError() || path.contains(0))
{
QString message(QString("GLC_3dxmlToWorld::loadOccurencePath An error occur in ") + m_FileName);
GLC_FileFormatException fileFormatException(message, m_FileName, GLC_FileFormatException::WrongFileFormat);
clear();
throw(fileFormatException);
}
return path;
}
void GLC_3dxmlToWorld::loadGraphicProperties(V4OccurenceAttrib* pAttrib)
{
while(endElementNotReached(m_pStreamReader, "GraphicProperties"))
{
if ((QXmlStreamReader::StartElement == m_pStreamReader->tokenType()) && (m_pStreamReader->name() == "GeneralAttributes"))
{
QString visibleString= readAttribute("visible", true);
if (visibleString != "true")
{
pAttrib->m_IsVisible= false;
}
}
else if ((QXmlStreamReader::StartElement == m_pStreamReader->tokenType()) && (m_pStreamReader->name() == "SurfaceAttributes"))
{
goToElement(m_pStreamReader, "Color");
const double red= readAttribute("red", true).toDouble();
const double green= readAttribute("green", true).toDouble();
const double blue= readAttribute("blue", true).toDouble();
double alpha= 1.0;
QString alphaString= readAttribute("alpha", false);
if (!alphaString.isEmpty()) alpha= alphaString.toDouble();
GLC_RenderProperties* pRenderProperties= new GLC_RenderProperties();
if (red != -1.0f)
{
QColor diffuseColor;
diffuseColor.setRgbF(red, green, blue, alpha);
GLC_Material* pMaterial= new GLC_Material();
pMaterial->setDiffuseColor(diffuseColor);
pRenderProperties->setOverwriteMaterial(pMaterial);
pRenderProperties->setRenderingMode(glc::OverwriteMaterial);
}
else if (alpha < 1.0f)
{
pRenderProperties->setOverwriteTransparency(static_cast<float>(alpha));
pRenderProperties->setRenderingMode(glc::OverwriteTransparency);
}
pAttrib->m_pRenderProperties= pRenderProperties;
}
readNext();
}
}
// Load the extern representation // Load the extern representation
void GLC_3dxmlToWorld::loadExternRepresentations() void GLC_3dxmlToWorld::loadExternRepresentations()
{ {
@ -1734,7 +1794,6 @@ void GLC_3dxmlToWorld::loadExternRepresentations()
GLC_BSRep binaryRep= cacheManager.binary3DRep(QFileInfo(m_FileName).baseName(), m_CurrentFileName); GLC_BSRep binaryRep= cacheManager.binary3DRep(QFileInfo(m_FileName).baseName(), m_CurrentFileName);
representation= binaryRep.loadRep(); representation= binaryRep.loadRep();
setRepresentationFileName(&representation); setRepresentationFileName(&representation);
factorizeMaterial(&representation);
} }
else else
{ {
@ -1853,110 +1912,8 @@ GLC_3DRep GLC_3dxmlToWorld::loadCurrentExtRep()
currentMeshRep.addGeom(pMesh); currentMeshRep.addGeom(pMesh);
} }
// Get the master lod accuracy loadRep(pMesh);
double masteLodAccuracy= readAttribute("accuracy", false).toDouble();
loadLOD(pMesh);
if (m_pStreamReader->atEnd() || m_pStreamReader->hasError())
{
QStringList stringList(m_FileName);
stringList.append(m_CurrentFileName);
stringList.append("Master LOD not found");
GLC_ErrorLog::addError(stringList);
pMesh->finish();
currentMeshRep.clean();
if (GLC_State::cacheIsUsed())
{
GLC_CacheManager currentManager= GLC_State::currentCacheManager();
currentManager.addToCache(QFileInfo(m_FileName).baseName(), currentMeshRep);
}
return currentMeshRep;
}
// Load Faces index data
while (endElementNotReached(m_pStreamReader, "Faces"))
{
readNext();;
if ( m_pStreamReader->name() == "Face")
{
loadFace(pMesh, 0, masteLodAccuracy);
}
}
checkForXmlError("End of Faces not found");
while (startElementNotReached(m_pStreamReader, "Edges") && startElementNotReached(m_pStreamReader, "VertexBuffer"))
{
readNext();;
}
checkForXmlError("Element VertexBuffer not found");
if (m_pStreamReader->name() == "Edges")
{
while (endElementNotReached(m_pStreamReader, "Edges"))
{
readNext();;
if ( m_pStreamReader->name() == "Polyline")
{
loadPolyline(pMesh);
readNext();;
}
}
}
{
QString verticePosition= getContent(m_pStreamReader, "Positions").replace(',', ' ');
//qDebug() << "Position " << verticePosition;
checkForXmlError("Error while retrieving Position ContentVertexBuffer");
// Load Vertice position
QTextStream verticeStream(&verticePosition);
QList<GLfloat> verticeValues;
QString buff;
while ((!verticeStream.atEnd()))
{
verticeStream >> buff;
verticeValues.append(buff.toFloat());
}
pMesh->addVertice(verticeValues.toVector());
}
{
QString normals= getContent(m_pStreamReader, "Normals").replace(',', ' ');
//qDebug() << "Normals " << normals;
checkForXmlError("Error while retrieving Normals values");
// Load Vertice Normals
QTextStream normalsStream(&normals);
QList<GLfloat> normalValues;
QString buff;
while ((!normalsStream.atEnd()))
{
normalsStream >> buff;
normalValues.append(buff.toFloat());
}
pMesh->addNormals(normalValues.toVector());
}
// Try to find texture coordinate
while (endElementNotReached(m_pStreamReader, "VertexBuffer"))
{
if ((QXmlStreamReader::StartElement == m_pStreamReader->tokenType()) && (m_pStreamReader->name() == "TextureCoordinates"))
{
QString texels= getContent(m_pStreamReader, "TextureCoordinates").replace(',', ' ');
checkForXmlError("Error while retrieving Texture coordinates");
QTextStream texelStream(&texels);
QList<GLfloat> texelValues;
QString buff;
while ((!texelStream.atEnd()))
{
texelStream >> buff;
texelValues.append(buff.toFloat());
}
pMesh->addTexels(texelValues.toVector());
}
readNext();;
}
++numberOfMesh; ++numberOfMesh;
} }
@ -2001,7 +1958,7 @@ void GLC_3dxmlToWorld::loadCatMaterialRef()
//qDebug() << "Material " << currentMaterial.m_Name << " Added"; //qDebug() << "Material " << currentMaterial.m_Name << " Added";
} }
} }
readNext();; readNext();
} }
} }
// Load material files // Load material files
@ -2024,7 +1981,7 @@ void GLC_3dxmlToWorld::loadMaterialDef(const MaterialRef& materialRef)
checkForXmlError(QString("Element Osm not found in file : ") + materialRef.m_AssociatedFile); checkForXmlError(QString("Element Osm not found in file : ") + materialRef.m_AssociatedFile);
while (endElementNotReached(m_pStreamReader, "Osm")) while (endElementNotReached(m_pStreamReader, "Osm"))
{ {
readNext();; readNext();
if ((QXmlStreamReader::StartElement == m_pStreamReader->tokenType()) && m_pStreamReader->name() == "Attr") if ((QXmlStreamReader::StartElement == m_pStreamReader->tokenType()) && m_pStreamReader->name() == "Attr")
{ {
const QString currentName= readAttribute("Name", true); const QString currentName= readAttribute("Name", true);
@ -2121,7 +2078,7 @@ void GLC_3dxmlToWorld::loadCatRepImage()
m_TextureImagesHash.insert(id,associatedFile); m_TextureImagesHash.insert(id,associatedFile);
} }
} }
readNext();; readNext();
} }
//qDebug() << "CATRepImage.3dxml Load"; //qDebug() << "CATRepImage.3dxml Load";
} }
@ -2187,7 +2144,7 @@ GLC_Texture* GLC_3dxmlToWorld::loadTexture(QString fileName)
GLC_Texture* pTexture= NULL; GLC_Texture* pTexture= NULL;
if (!resultImage.isNull()) if (!resultImage.isNull())
{ {
pTexture= new GLC_Texture(m_pQGLContext, resultImage, resultImageFileName); pTexture= new GLC_Texture(resultImage, resultImageFileName);
} }
else else
{ {
@ -2199,47 +2156,6 @@ GLC_Texture* GLC_3dxmlToWorld::loadTexture(QString fileName)
return pTexture; return pTexture;
} }
// Factorize material use
void GLC_3dxmlToWorld::factorizeMaterial(GLC_3DRep* pRep)
{
//qDebug() << "GLC_3dxmlToWorld::factorizeMaterial";
// Get the Set of materials of the rep
QSet<GLC_Material*> repMaterialSet= pRep->materialSet();
//! The hash table of rep material
QHash<GLC_uint, GLC_Material*> repMaterialHash;
// Construct the map of material String Hash and Id
QHash<QString, GLC_uint> materialMap;
{ // Fill the map of material
QSet<GLC_Material*>::const_iterator iMat= repMaterialSet.constBegin();
while(repMaterialSet.constEnd() != iMat)
{
GLC_Material* pCurrentMat= *iMat;
materialMap.insert(QString::number(pCurrentMat->hashCode()), pCurrentMat->id());
repMaterialHash.insert(pCurrentMat->id(), pCurrentMat);
++iMat;
}
}
// Make the factorization
QHash<QString, GLC_uint>::iterator iMat= materialMap.begin();
while (materialMap.constEnd() != iMat)
{
if (m_MaterialHash.contains(iMat.key()))
{
//qDebug() << "Replace Mat :" << iMat.key() << " " << iMat.value();
pRep->replaceMaterial(iMat.value(), m_MaterialHash.value(iMat.key()));
}
else
{
//qDebug() << "Indert mat " << iMat.key() << " " << iMat.value();
m_MaterialHash.insert(iMat.key(), repMaterialHash.value(iMat.value()));
}
++iMat;
}
}
void GLC_3dxmlToWorld::setRepresentationFileName(GLC_3DRep* pRep) void GLC_3dxmlToWorld::setRepresentationFileName(GLC_3DRep* pRep)
{ {
if (m_IsInArchive) if (m_IsInArchive)
@ -2267,3 +2183,235 @@ void GLC_3dxmlToWorld::checkFileValidity(QIODevice* pIODevice)
pIODevice->seek(0); pIODevice->seek(0);
} }
} }
void GLC_3dxmlToWorld::applyV4Attribute(GLC_StructOccurence* pOccurence, V4OccurenceAttrib* pV4OccurenceAttrib, QHash<GLC_StructInstance*, unsigned int>& instanceToIdHash)
{
Q_ASSERT(pOccurence->hasChild() && !pV4OccurenceAttrib->m_Path.isEmpty());
unsigned int id= pV4OccurenceAttrib->m_Path.takeFirst();
const int childCount= pOccurence->childCount();
bool occurenceFound= false;
int i= 0;
while (!occurenceFound && (i < childCount))
{
GLC_StructOccurence* pChildOccurence= pOccurence->child(i);
if (instanceToIdHash.contains(pChildOccurence->structInstance()) && (instanceToIdHash.value(pChildOccurence->structInstance()) == id))
{
Q_ASSERT(id == instanceToIdHash.value(pChildOccurence->structInstance()));
occurenceFound= true;
if (pV4OccurenceAttrib->m_Path.isEmpty())
{
pChildOccurence->setVisibility(pV4OccurenceAttrib->m_IsVisible);
if (NULL != pV4OccurenceAttrib->m_pRenderProperties)
{
pChildOccurence->setRenderProperties(*(pV4OccurenceAttrib->m_pRenderProperties));
}
if (pV4OccurenceAttrib->m_pMatrix != NULL)
{
pChildOccurence->makeFlexible(*(pV4OccurenceAttrib->m_pMatrix));
}
}
else
{
applyV4Attribute(pChildOccurence, pV4OccurenceAttrib, instanceToIdHash);
}
}
else
{
++i;
}
}
if (!occurenceFound)
{
qDebug() << "GLC_3dxmlToWorld::applyV4Attribute Occurrence not found" << id;
}
}
void GLC_3dxmlToWorld::loadRep(GLC_Mesh* pMesh)
{
double masteLodAccuracy= readAttribute("accuracy", false).toDouble();
int lodIndex= 1;
bool masterLodFound= false;
bool vertexBufferFound= false;
while (endElementNotReached(m_pStreamReader, "Rep") && endElementNotReached(m_pStreamReader, "Root"))
{
if ((QXmlStreamReader::StartElement == m_pStreamReader->tokenType()))
{
if (m_pStreamReader->name() == "SurfaceAttributes")
{
m_pCurrentMaterial= loadSurfaceAttributes();
}
else if (m_pStreamReader->name() == "PolygonalLOD")
{
double accuracy= readAttribute("accuracy", true).toDouble();
while (endElementNotReached(m_pStreamReader, "Faces"))
{
readNext();
if ( m_pStreamReader->name() == "Face")
{
loadFace(pMesh, lodIndex, accuracy);
}
}
checkForXmlError("End of Faces not found");
++lodIndex;
}
else if (m_pStreamReader->name() == "Faces")
{
masterLodFound= true;
while (endElementNotReached(m_pStreamReader, "Faces"))
{
readNext();
if ( m_pStreamReader->name() == "Face")
{
loadFace(pMesh, 0, masteLodAccuracy);
}
}
checkForXmlError("End of Faces not found");
}
else if (m_pStreamReader->name() == "Edges")
{
while (endElementNotReached(m_pStreamReader, "Edges"))
{
readNext();
if ( m_pStreamReader->name() == "Polyline")
{
loadPolyline(pMesh);
readNext();
}
}
}
else if (m_pStreamReader->name() == "VertexBuffer")
{
vertexBufferFound= true;
loadVertexBuffer(pMesh);
}
else readNext();
}
else
{
readNext();
}
}
checkForXmlError("End of Rep or Root not found");
if (!masterLodFound || !vertexBufferFound)
{
QString message;
if (!masterLodFound)
{
message= QString("Master LOD not found in file ") + m_FileName;
}
else
{
message= QString("Vertex Buffer not found in file ") + m_FileName;
}
GLC_FileFormatException fileFormatException(message, m_FileName, GLC_FileFormatException::WrongFileFormat);
clear();
throw(fileFormatException);
}
}
void GLC_3dxmlToWorld::loadVertexBuffer(GLC_Mesh* pMesh)
{
{
QString verticePosition= getContent(m_pStreamReader, "Positions").replace(',', ' ');
//qDebug() << "Position " << verticePosition;
checkForXmlError("Error while retrieving Position ContentVertexBuffer");
// Load Vertice position
QTextStream verticeStream(&verticePosition);
QList<GLfloat> verticeValues;
QString buff;
while ((!verticeStream.atEnd()))
{
verticeStream >> buff;
verticeValues.append(buff.toFloat());
}
if ((verticeValues.size() % 3) == 0)
{
pMesh->addVertice(verticeValues.toVector());
}
else
{
QString message(QString("Vertice buffer is not a multiple of 3 ") + m_CurrentFileName);
QStringList stringList(message);
GLC_ErrorLog::addError(stringList);
GLC_FileFormatException fileFormatException(message, m_FileName, GLC_FileFormatException::WrongFileFormat);
clear();
throw(fileFormatException);
}
}
{
QString normals= getContent(m_pStreamReader, "Normals").replace(',', ' ');
//qDebug() << "Normals " << normals;
checkForXmlError("Error while retrieving Normals values");
// Load Vertice Normals
QTextStream normalsStream(&normals);
QList<GLfloat> normalValues;
QString buff;
while ((!normalsStream.atEnd()))
{
normalsStream >> buff;
normalValues.append(buff.toFloat());
}
if ((normalValues.size() % 3) == 0)
{
pMesh->addNormals(normalValues.toVector());
}
else
{
QString message(QString("Normal buffer is not a multiple of 3 ") + m_CurrentFileName);
QStringList stringList(message);
GLC_ErrorLog::addError(stringList);
GLC_FileFormatException fileFormatException(message, m_FileName, GLC_FileFormatException::WrongFileFormat);
clear();
throw(fileFormatException);
}
}
// Try to find texture coordinate
while (endElementNotReached(m_pStreamReader, "VertexBuffer"))
{
if ((QXmlStreamReader::StartElement == m_pStreamReader->tokenType()) && (m_pStreamReader->name() == "TextureCoordinates"))
{
QString texels= getContent(m_pStreamReader, "TextureCoordinates").replace(',', ' ');
checkForXmlError("Error while retrieving Texture coordinates");
QTextStream texelStream(&texels);
QList<GLfloat> texelValues;
QString buff;
while ((!texelStream.atEnd()))
{
texelStream >> buff;
texelValues.append(buff.toFloat());
}
if ((texelValues.size() % 2) == 0)
{
pMesh->addTexels(texelValues.toVector());
}
else
{
QString message(QString("Texel buffer is not a multiple of 2 ") + m_CurrentFileName);
QStringList stringList(message);
GLC_ErrorLog::addError(stringList);
GLC_FileFormatException fileFormatException(message, m_FileName, GLC_FileFormatException::WrongFileFormat);
clear();
throw(fileFormatException);
}
}
readNext();
}
checkForXmlError("VertexBuffer not found");
}

View File

@ -34,7 +34,7 @@
#include "../maths/glc_matrix4x4.h" #include "../maths/glc_matrix4x4.h"
#include "../sceneGraph/glc_3dviewinstance.h" #include "../sceneGraph/glc_3dviewinstance.h"
#include "glc_config.h" #include "../glc_config.h"
class GLC_World; class GLC_World;
class QGLContext; class QGLContext;
@ -42,6 +42,7 @@ class QuaZip;
class QuaZipFile; class QuaZipFile;
class GLC_StructReference; class GLC_StructReference;
class GLC_StructInstance; class GLC_StructInstance;
class GLC_StructOccurence;
class GLC_Mesh; class GLC_Mesh;
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -78,15 +79,15 @@ class GLC_LIB_EXPORT GLC_3dxmlToWorld : public QObject
QString m_AssociatedFile; QString m_AssociatedFile;
}; };
//! \class OccurenceAttrib //! \class V3OccurenceAttrib
/*! \brief OccurenceAttrib : Specifique occurence attribute */ /*! \brief V3OccurenceAttrib : Specifique occurence attribute */
struct OccurenceAttrib struct V3OccurenceAttrib
{ {
inline OccurenceAttrib() inline V3OccurenceAttrib()
: m_IsVisible(true) : m_IsVisible(true)
, m_pRenderProperties(NULL) , m_pRenderProperties(NULL)
{} {}
inline ~OccurenceAttrib() inline ~V3OccurenceAttrib()
{delete m_pRenderProperties;} {delete m_pRenderProperties;}
//! Visibility attribute //! Visibility attribute
@ -95,6 +96,32 @@ class GLC_LIB_EXPORT GLC_3dxmlToWorld : public QObject
GLC_RenderProperties* m_pRenderProperties; GLC_RenderProperties* m_pRenderProperties;
}; };
//! \class V3OccurenceAttrib
/*! \brief V3OccurenceAttrib : Specifique occurence attribute */
struct V4OccurenceAttrib
{
inline V4OccurenceAttrib()
: m_IsVisible(true)
, m_pRenderProperties(NULL)
, m_pMatrix(NULL)
, m_Path()
{}
inline ~V4OccurenceAttrib()
{
delete m_pRenderProperties;
delete m_pMatrix;
}
//! Visibility attribute
bool m_IsVisible;
//! Render properties attribute
GLC_RenderProperties* m_pRenderProperties;
//! Relative matrix
GLC_Matrix4x4* m_pMatrix;
//! The path of this attrib
QList<unsigned int> m_Path;
};
typedef QHash<unsigned int, GLC_StructReference*> ReferenceHash; typedef QHash<unsigned int, GLC_StructReference*> ReferenceHash;
typedef QHash<GLC_StructInstance*, unsigned int> InstanceOfHash; typedef QHash<GLC_StructInstance*, unsigned int> InstanceOfHash;
typedef QHash<GLC_StructInstance*, QString> InstanceOfExtRefHash; typedef QHash<GLC_StructInstance*, QString> InstanceOfExtRefHash;
@ -111,7 +138,7 @@ class GLC_LIB_EXPORT GLC_3dxmlToWorld : public QObject
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
public: public:
//! Default constructor //! Default constructor
GLC_3dxmlToWorld(const QGLContext*); GLC_3dxmlToWorld();
virtual ~GLC_3dxmlToWorld(); virtual ~GLC_3dxmlToWorld();
//@} //@}
@ -159,6 +186,9 @@ private:
//! Read the specified attribute //! Read the specified attribute
QString readAttribute(const QString&, bool required= false); QString readAttribute(const QString&, bool required= false);
//! Read the Header
void readHeader();
//! Load the product structure //! Load the product structure
void loadProductStructure(); void loadProductStructure();
@ -190,9 +220,6 @@ private:
//! Throw ecxeption if error occur //! Throw ecxeption if error occur
void checkForXmlError(const QString&); void checkForXmlError(const QString&);
//! Load Level of detail
void loadLOD(GLC_Mesh*);
//! Load a face //! Load a face
void loadFace(GLC_Mesh*, const int lod, double accuracy); void loadFace(GLC_Mesh*, const int lod, double accuracy);
@ -211,11 +238,20 @@ private:
//! Set the stream reader to the specified file //! Set the stream reader to the specified file
bool setStreamReaderToFile(QString, bool test= false); bool setStreamReaderToFile(QString, bool test= false);
//! Load graphics properties //! Load default view element
void loadGraphicsProperties(); void loadDefaultView();
//! Load default view property //! Load 3DXML V3 default view property
void loadDefaultViewProperty(); void loadV3DefaultViewProperty();
//! Load 3DXML V4 default view property
void loadV4DefaultViewProperty();
//! Return the occurence path of the current DefaultViewProperty
QList<unsigned int> loadOccurencePath();
//! Load Graphics properties element
void loadGraphicProperties(V4OccurenceAttrib* pAttrib);
//! Load the local representation //! Load the local representation
void loadLocalRepresentations(); void loadLocalRepresentations();
@ -238,9 +274,6 @@ private:
//! Try to construct a texture with the specified fileName //! Try to construct a texture with the specified fileName
GLC_Texture* loadTexture(QString); GLC_Texture* loadTexture(QString);
//! Factorize material use
void factorizeMaterial(GLC_3DRep*);
//! Set fileName of the given 3DRep //! Set fileName of the given 3DRep
void setRepresentationFileName(GLC_3DRep* pRep); void setRepresentationFileName(GLC_3DRep* pRep);
@ -268,15 +301,21 @@ private:
//! Check if the given file is binary //! Check if the given file is binary
void checkFileValidity(QIODevice* pIODevice); void checkFileValidity(QIODevice* pIODevice);
//! Apply the given attribute to the right occurence from the given occurence
void applyV4Attribute(GLC_StructOccurence* pOccurence, V4OccurenceAttrib* pV4OccurenceAttrib, QHash<GLC_StructInstance*, unsigned int>& InstanceToIdHash);
//! Load representation from 3DRep file
void loadRep(GLC_Mesh* pMesh);
//! Load The 3DXML vertex buffer
void loadVertexBuffer(GLC_Mesh* pMesh);
//@} //@}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Private members // Private members
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
private: private:
//! OpenGL Context
const QGLContext* m_pQGLContext;
//! Xml Reader //! Xml Reader
QXmlStreamReader* m_pStreamReader; QXmlStreamReader* m_pStreamReader;
@ -349,8 +388,11 @@ private:
//! The current file time and date //! The current file time and date
QDateTime m_CurrentDateTime; QDateTime m_CurrentDateTime;
//! Hash table of occurence specific attributes //! Hash table of occurence specific attributes for 3DXML V3
QHash<unsigned int, OccurenceAttrib*> m_OccurenceAttrib; QHash<unsigned int, V3OccurenceAttrib*> m_V3OccurenceAttribHash;
//! List of occurence specific attributes for 3DXML V4
QList<V4OccurenceAttrib*> m_V4OccurenceAttribList;
//! bool get external ref 3D name //! bool get external ref 3D name
bool m_GetExternalRef3DName; bool m_GetExternalRef3DName;
@ -359,6 +401,9 @@ private:
QList<QByteArray> m_ByteArrayList; QList<QByteArray> m_ByteArrayList;
//! Flag to know if the 3DXML is in version 3.x
bool m_IsVersion3;
}; };
QXmlStreamReader::TokenType GLC_3dxmlToWorld::readNext() QXmlStreamReader::TokenType GLC_3dxmlToWorld::readNext()

View File

@ -33,13 +33,12 @@ static int currentNodeId= 0;
using namespace glcXmlUtil; using namespace glcXmlUtil;
// Default constructor // Default constructor
GLC_ColladaToWorld::GLC_ColladaToWorld(const QGLContext* pContext) GLC_ColladaToWorld::GLC_ColladaToWorld()
: QObject() : QObject()
, m_pWorld(NULL) , m_pWorld(NULL)
, m_pQGLContext(pContext)
, m_pStreamReader(NULL) , m_pStreamReader(NULL)
, m_FileName() , m_FileName()
, m_pFile() , m_pFile(NULL)
, m_ImageFileHash() , m_ImageFileHash()
, m_MaterialLibHash() , m_MaterialLibHash()
, m_SurfaceImageHash() , m_SurfaceImageHash()
@ -68,7 +67,7 @@ GLC_ColladaToWorld::GLC_ColladaToWorld(const QGLContext* pContext)
// Destructor // Destructor
GLC_ColladaToWorld::~GLC_ColladaToWorld() GLC_ColladaToWorld::~GLC_ColladaToWorld()
{ {
// Normal ends, wold has not to be deleted // Normal ends, world has not to be deleted
m_pWorld= NULL; m_pWorld= NULL;
clear(); clear();
} }
@ -138,6 +137,10 @@ GLC_World* GLC_ColladaToWorld::CreateWorldFromCollada(QFile &file)
m_pStreamReader->readNext(); m_pStreamReader->readNext();
} }
m_pFile->close();
m_pFile= NULL;
// Link the textures to materials // Link the textures to materials
linkTexturesToMaterials(); linkTexturesToMaterials();
@ -233,10 +236,11 @@ void GLC_ColladaToWorld::clear()
delete m_pWorld; delete m_pWorld;
m_pWorld= NULL; m_pWorld= NULL;
delete m_pStreamReader; delete m_pStreamReader;
m_pStreamReader= NULL; m_pStreamReader= NULL;
if (NULL != m_pFile) m_pFile->close(); if (m_pFile != NULL) m_pFile->close();
m_pFile= NULL; m_pFile= NULL;
m_ImageFileHash.clear(); m_ImageFileHash.clear();
@ -1792,7 +1796,7 @@ void GLC_ColladaToWorld::linkTexturesToMaterials()
if (QFileInfo(fullImageFileName).exists()) if (QFileInfo(fullImageFileName).exists())
{ {
m_ListOfAttachedFileName << fullImageFileName; m_ListOfAttachedFileName << fullImageFileName;
GLC_Texture* pTexture= new GLC_Texture(m_pQGLContext, fullImageFileName); GLC_Texture* pTexture= new GLC_Texture(fullImageFileName);
pCurrentMaterial->setTexture(pTexture); pCurrentMaterial->setTexture(pTexture);
} }
else if (QFileInfo(m_FileName).absolutePath() != QFileInfo(fullImageFileName).absolutePath()) else if (QFileInfo(m_FileName).absolutePath() != QFileInfo(fullImageFileName).absolutePath())
@ -1802,7 +1806,7 @@ void GLC_ColladaToWorld::linkTexturesToMaterials()
if (QFileInfo(fullImageFileName).exists()) if (QFileInfo(fullImageFileName).exists())
{ {
m_ListOfAttachedFileName << fullImageFileName; m_ListOfAttachedFileName << fullImageFileName;
GLC_Texture* pTexture= new GLC_Texture(m_pQGLContext, fullImageFileName); GLC_Texture* pTexture= new GLC_Texture(fullImageFileName);
pCurrentMaterial->setTexture(pTexture); pCurrentMaterial->setTexture(pTexture);
} }
else else

View File

@ -161,7 +161,7 @@ private:
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
public: public:
//! Default constructor //! Default constructor
GLC_ColladaToWorld(const QGLContext*); GLC_ColladaToWorld();
//! Destructor //! Destructor
virtual ~GLC_ColladaToWorld(); virtual ~GLC_ColladaToWorld();
@ -368,9 +368,6 @@ private:
//! The world to built //! The world to built
GLC_World* m_pWorld; GLC_World* m_pWorld;
//! OpenGL Context
const QGLContext* m_pQGLContext;
//! Xml Reader //! Xml Reader
QXmlStreamReader* m_pStreamReader; QXmlStreamReader* m_pStreamReader;

View File

@ -42,8 +42,7 @@
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Constructor // Constructor
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
GLC_FileLoader::GLC_FileLoader(const QGLContext *pContext) GLC_FileLoader::GLC_FileLoader()
: m_pQGLContext(pContext)
{ {
} }
@ -89,7 +88,7 @@ GLC_World GLC_FileLoader::createWorldFromFile(QFile &file, QStringList* pAttache
GLC_World* pWorld= NULL; GLC_World* pWorld= NULL;
if (QFileInfo(file).suffix().toLower() == "obj") if (QFileInfo(file).suffix().toLower() == "obj")
{ {
GLC_ObjToWorld objToWorld(m_pQGLContext); GLC_ObjToWorld objToWorld;
connect(&objToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int))); connect(&objToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));
pWorld= objToWorld.CreateWorldFromObj(file); pWorld= objToWorld.CreateWorldFromObj(file);
if (NULL != pAttachedFileName) if (NULL != pAttachedFileName)
@ -111,7 +110,7 @@ GLC_World GLC_FileLoader::createWorldFromFile(QFile &file, QStringList* pAttache
} }
else if (QFileInfo(file).suffix().toLower() == "3ds") else if (QFileInfo(file).suffix().toLower() == "3ds")
{ {
GLC_3dsToWorld studioToWorld(m_pQGLContext); GLC_3dsToWorld studioToWorld;
connect(&studioToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int))); connect(&studioToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));
pWorld= studioToWorld.CreateWorldFrom3ds(file); pWorld= studioToWorld.CreateWorldFrom3ds(file);
if (NULL != pAttachedFileName) if (NULL != pAttachedFileName)
@ -121,7 +120,7 @@ GLC_World GLC_FileLoader::createWorldFromFile(QFile &file, QStringList* pAttache
} }
else if (QFileInfo(file).suffix().toLower() == "3dxml") else if (QFileInfo(file).suffix().toLower() == "3dxml")
{ {
GLC_3dxmlToWorld d3dxmlToWorld(m_pQGLContext); GLC_3dxmlToWorld d3dxmlToWorld;
connect(&d3dxmlToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int))); connect(&d3dxmlToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));
pWorld= d3dxmlToWorld.createWorldFrom3dxml(file, false); pWorld= d3dxmlToWorld.createWorldFrom3dxml(file, false);
if (NULL != pAttachedFileName) if (NULL != pAttachedFileName)
@ -131,7 +130,7 @@ GLC_World GLC_FileLoader::createWorldFromFile(QFile &file, QStringList* pAttache
} }
else if (QFileInfo(file).suffix().toLower() == "dae") else if (QFileInfo(file).suffix().toLower() == "dae")
{ {
GLC_ColladaToWorld colladaToWorld(m_pQGLContext); GLC_ColladaToWorld colladaToWorld;
connect(&colladaToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int))); connect(&colladaToWorld, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));
pWorld= colladaToWorld.CreateWorldFromCollada(file); pWorld= colladaToWorld.CreateWorldFromCollada(file);
if (NULL != pAttachedFileName) if (NULL != pAttachedFileName)

View File

@ -56,7 +56,7 @@ class GLC_LIB_EXPORT GLC_FileLoader : public QObject
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
public: public:
GLC_FileLoader(const QGLContext*); GLC_FileLoader();
virtual ~GLC_FileLoader(); virtual ~GLC_FileLoader();
//@} //@}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -79,8 +79,6 @@ public:
// Private members // Private members
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
private: private:
//! OpenGL Context
const QGLContext* m_pQGLContext;
}; };
#endif /*GLC_FILELOADER_H_*/ #endif /*GLC_FILELOADER_H_*/

View File

@ -32,12 +32,11 @@
#include <QtDebug> #include <QtDebug>
#include <QGLContext> #include <QGLContext>
GLC_ObjMtlLoader::GLC_ObjMtlLoader(const QGLContext *pContext, const QString& fileName) GLC_ObjMtlLoader::GLC_ObjMtlLoader(const QString& fileName)
: m_FileName(fileName) : m_FileName(fileName)
, m_pCurrentMaterial(NULL) , m_pCurrentMaterial(NULL)
, m_Materials() , m_Materials()
, m_LoadStatus() , m_LoadStatus()
, m_pQGLContext(pContext)
, m_ListOfAttachedFileName() , m_ListOfAttachedFileName()
{ {
} }
@ -214,7 +213,7 @@ void GLC_ObjMtlLoader::extractTextureFileName(QString &ligne)
{ {
m_ListOfAttachedFileName << textureFileName; m_ListOfAttachedFileName << textureFileName;
// Create the texture and assign it to current material // Create the texture and assign it to current material
GLC_Texture *pTexture = new GLC_Texture(m_pQGLContext, textureFile); GLC_Texture *pTexture = new GLC_Texture(textureFile);
m_pCurrentMaterial->setTexture(pTexture); m_pCurrentMaterial->setTexture(pTexture);
//qDebug() << "Texture File is : " << valueString; //qDebug() << "Texture File is : " << valueString;
} }

View File

@ -50,7 +50,7 @@ class GLC_LIB_EXPORT GLC_ObjMtlLoader
//@{ //@{
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
public: public:
GLC_ObjMtlLoader(const QGLContext*, const QString&); GLC_ObjMtlLoader(const QString&);
virtual ~GLC_ObjMtlLoader(); virtual ~GLC_ObjMtlLoader();
//@} //@}
@ -123,9 +123,6 @@ private:
//! the Load status //! the Load status
QString m_LoadStatus; QString m_LoadStatus;
//! OpenGL Context
const QGLContext *m_pQGLContext;
//! The list of attached file name //! The list of attached file name
QSet<QString> m_ListOfAttachedFileName; QSet<QString> m_ListOfAttachedFileName;

View File

@ -40,10 +40,9 @@
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Constructor // Constructor
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
GLC_ObjToWorld::GLC_ObjToWorld(const QGLContext *pContext) GLC_ObjToWorld::GLC_ObjToWorld()
: m_pWorld(NULL) : m_pWorld(NULL)
, m_FileName() , m_FileName()
, m_pQGLContext(pContext)
, m_pMtlLoader(NULL) , m_pMtlLoader(NULL)
, m_CurrentLineNumber(0) , m_CurrentLineNumber(0)
, m_pCurrentObjMesh(NULL) , m_pCurrentObjMesh(NULL)
@ -131,7 +130,7 @@ GLC_World* GLC_ObjToWorld::CreateWorldFromObj(QFile &file)
QString mtlLibFileName(getMtlLibFileName(mtlLibLine)); QString mtlLibFileName(getMtlLibFileName(mtlLibLine));
if (!mtlLibFileName.isEmpty()) if (!mtlLibFileName.isEmpty())
{ {
m_pMtlLoader= new GLC_ObjMtlLoader(m_pQGLContext, mtlLibFileName); m_pMtlLoader= new GLC_ObjMtlLoader(mtlLibFileName);
if (!m_pMtlLoader->loadMaterials()) if (!m_pMtlLoader->loadMaterials())
{ {
delete m_pMtlLoader; delete m_pMtlLoader;

View File

@ -150,7 +150,7 @@ public:
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
public: public:
GLC_ObjToWorld(const QGLContext*); GLC_ObjToWorld();
virtual ~GLC_ObjToWorld(); virtual ~GLC_ObjToWorld();
//@} //@}
@ -227,9 +227,6 @@ private:
//! The Obj File name //! The Obj File name
QString m_FileName; QString m_FileName;
//! OpenGL Context
const QGLContext* m_pQGLContext;
//! the Obj Mtl loader //! the Obj Mtl loader
GLC_ObjMtlLoader* m_pMtlLoader; GLC_ObjMtlLoader* m_pMtlLoader;

View File

@ -23,8 +23,8 @@
#include "glc_worldto3dxml.h" #include "glc_worldto3dxml.h"
// Quazip library // Quazip library
#include "../quazip/quazip.h" #include "../3rdparty/quazip/quazip.h"
#include "../quazip/quazipfile.h" #include "../3rdparty/quazip/quazipfile.h"
#include "../glc_exception.h" #include "../glc_exception.h"
#include "../geometry/glc_mesh.h" #include "../geometry/glc_mesh.h"
@ -405,7 +405,7 @@ void GLC_WorldTo3dxml::exportAssemblyFromOccurence(const GLC_StructOccurence* pO
GLC_3DViewInstance* pInstance= m_World.collection()->instanceHandle(pOccurence->id()); GLC_3DViewInstance* pInstance= m_World.collection()->instanceHandle(pOccurence->id());
Q_ASSERT(NULL != pInstance); Q_ASSERT(NULL != pInstance);
const bool isVisible= pInstance->isVisible(); const bool isVisible= pInstance->isVisible();
const bool isOverload= !isVisible || !pInstance->renderPropertiesHandle()->isDefault(); const bool isOverload= !isVisible || !pInstance->renderPropertiesHandle()->isDefault() || pOccurence->isFlexible();
if (isOverload) if (isOverload)
{ {
m_ListOfOverLoadedOccurence.append(pOccurence); m_ListOfOverLoadedOccurence.append(pOccurence);
@ -419,22 +419,22 @@ QString GLC_WorldTo3dxml::matrixString(const GLC_Matrix4x4& matrix)
QString resultMatrix; QString resultMatrix;
const QChar spaceChar(' '); const QChar spaceChar(' ');
// Rotation // Rotation
resultMatrix+= QString::number(matrix.getData()[0]) + spaceChar; resultMatrix+= QString::number(matrix.getData()[0], 'g', 16) + spaceChar;
resultMatrix+= QString::number(matrix.getData()[1]) + spaceChar; resultMatrix+= QString::number(matrix.getData()[1], 'g', 16) + spaceChar;
resultMatrix+= QString::number(matrix.getData()[2]) + spaceChar; resultMatrix+= QString::number(matrix.getData()[2], 'g', 16) + spaceChar;
resultMatrix+= QString::number(matrix.getData()[4]) + spaceChar; resultMatrix+= QString::number(matrix.getData()[4], 'g', 16) + spaceChar;
resultMatrix+= QString::number(matrix.getData()[5]) + spaceChar; resultMatrix+= QString::number(matrix.getData()[5], 'g', 16) + spaceChar;
resultMatrix+= QString::number(matrix.getData()[6]) + spaceChar; resultMatrix+= QString::number(matrix.getData()[6], 'g', 16) + spaceChar;
resultMatrix+= QString::number(matrix.getData()[8]) + spaceChar; resultMatrix+= QString::number(matrix.getData()[8], 'g', 16) + spaceChar;
resultMatrix+= QString::number(matrix.getData()[9]) + spaceChar; resultMatrix+= QString::number(matrix.getData()[9], 'g', 16) + spaceChar;
resultMatrix+= QString::number(matrix.getData()[10]) + spaceChar; resultMatrix+= QString::number(matrix.getData()[10], 'g', 16) + spaceChar;
// Translation // Translation
resultMatrix+= QString::number(matrix.getData()[12]) + spaceChar; resultMatrix+= QString::number(matrix.getData()[12], 'g', 16) + spaceChar;
resultMatrix+= QString::number(matrix.getData()[13]) + spaceChar; resultMatrix+= QString::number(matrix.getData()[13], 'g', 16) + spaceChar;
resultMatrix+= QString::number(matrix.getData()[14]); resultMatrix+= QString::number(matrix.getData()[14], 'g', 16);
return resultMatrix; return resultMatrix;
} }
@ -772,7 +772,7 @@ void GLC_WorldTo3dxml::writeMaterial(const GLC_Material* pMaterial)
} }
else else
{ {
materialName= pMaterial->name(); materialName= symplifyName(pMaterial->name());
} }
@ -1105,17 +1105,30 @@ void GLC_WorldTo3dxml::addImageTextureTo3dxml(const QImage& image, const QString
} }
} }
QString GLC_WorldTo3dxml::xmlFileName(const QString& fileName) QString GLC_WorldTo3dxml::xmlFileName(QString fileName)
{ {
QString newName; QString prefix;
if (!m_3dxmlFileSet.contains(fileName)) if (fileName.contains("urn:3DXML:"))
{ {
prefix= "urn:3DXML:";
fileName.remove(prefix);
}
fileName= symplifyName(fileName);
QString newName;
if (!m_3dxmlFileSet.contains(prefix + fileName))
{
fileName.prepend(prefix);
m_3dxmlFileSet << fileName; m_3dxmlFileSet << fileName;
newName= fileName; newName= fileName;
} }
else else
{ {
newName= QFileInfo(fileName).completeBaseName() + QString::number(++m_FileNameIncrement) + '.' + QFileInfo(fileName).suffix(); newName= QFileInfo(fileName).completeBaseName() + QString::number(++m_FileNameIncrement) + '.' + QFileInfo(fileName).suffix();
newName.prepend(prefix);
} }
return newName; return newName;
} }
@ -1142,40 +1155,87 @@ void GLC_WorldTo3dxml::writeExtensionAttributes(GLC_Attributes* pAttributes)
void GLC_WorldTo3dxml::writeOccurenceDefaultViewProperty(const GLC_StructOccurence* pOccurence) void GLC_WorldTo3dxml::writeOccurenceDefaultViewProperty(const GLC_StructOccurence* pOccurence)
{ {
QList<unsigned int> path= instancePath(pOccurence);
GLC_3DViewInstance* pInstance= m_World.collection()->instanceHandle(pOccurence->id()); GLC_3DViewInstance* pInstance= m_World.collection()->instanceHandle(pOccurence->id());
Q_ASSERT(NULL != pInstance); Q_ASSERT(NULL != pInstance);
const bool isVisible= pOccurence->isVisible(); const bool isVisible= pOccurence->isVisible();
const unsigned int occurrenceId= pOccurence->occurenceNumber();
m_pOutStream->writeStartElement("DefaultViewProperty"); m_pOutStream->writeStartElement("DefaultViewProperty");
m_pOutStream->writeTextElement("OccurenceId", QString::number(occurrenceId)); m_pOutStream->writeStartElement("OccurenceId");
m_pOutStream->writeStartElement("GraphicProperties"); const QString prefix= "urn:3DXML:" + QFileInfo(m_FileName).fileName() + "#";
m_pOutStream->writeAttribute("xsi:type", "GraphicPropertiesType"); const int pathSize= path.size();
if (! isVisible) for (int i= 0; i < pathSize; ++i)
{ {
m_pOutStream->writeStartElement("GeneralAttributes"); m_pOutStream->writeTextElement("id", prefix + QString::number(path.at(i)));
m_pOutStream->writeAttribute("xsi:type", "GeneralAttributesType");
m_pOutStream->writeAttribute("visible", "false");
m_pOutStream->writeAttribute("selectable", "true");
m_pOutStream->writeEndElement(); // GeneralAttributes
} }
if (!pInstance->renderPropertiesHandle()->isDefault()) m_pOutStream->writeEndElement(); // OccurenceId
if (pOccurence->isFlexible())
{ {
const GLC_RenderProperties* pProperties= pInstance->renderPropertiesHandle(); m_pOutStream->writeTextElement("RelativePosition", matrixString(pOccurence->occurrenceRelativeMatrix()));
if (pProperties->overwriteTransparency() != -1.0f) }
if (!isVisible || !pInstance->renderPropertiesHandle()->isDefault())
{
qDebug() << "(!isVisible || !pInstance->renderPropertiesHandle()->isDefault())";
m_pOutStream->writeStartElement("GraphicProperties");
m_pOutStream->writeAttribute("xsi:type", "GraphicPropertiesType");
if (! isVisible)
{ {
m_pOutStream->writeStartElement("SurfaceAttributes"); m_pOutStream->writeStartElement("GeneralAttributes");
m_pOutStream->writeAttribute("xsi:type", "SurfaceAttributesType"); m_pOutStream->writeAttribute("xsi:type", "GeneralAttributesType");
m_pOutStream->writeStartElement("Color"); m_pOutStream->writeAttribute("visible", "false");
m_pOutStream->writeAttribute("xsi:type", "RGBAColorType"); m_pOutStream->writeAttribute("selectable", "true");
m_pOutStream->writeAttribute("red", "-1"); m_pOutStream->writeEndElement(); // GeneralAttributes
m_pOutStream->writeAttribute("green", "-1");
m_pOutStream->writeAttribute("blue", "-1");
m_pOutStream->writeAttribute("alpha", QString::number(pProperties->overwriteTransparency()));
m_pOutStream->writeEndElement(); // Color
m_pOutStream->writeEndElement(); // SurfaceAttributes
} }
if (!pInstance->renderPropertiesHandle()->isDefault())
{
const GLC_RenderProperties* pProperties= pInstance->renderPropertiesHandle();
if ((pProperties->renderingMode() == glc::OverwriteTransparency))
{
m_pOutStream->writeStartElement("SurfaceAttributes");
m_pOutStream->writeAttribute("xsi:type", "SurfaceAttributesType");
m_pOutStream->writeStartElement("Color");
m_pOutStream->writeAttribute("xsi:type", "RGBAColorType");
m_pOutStream->writeAttribute("red", "-1");
m_pOutStream->writeAttribute("green", "-1");
m_pOutStream->writeAttribute("blue", "-1");
m_pOutStream->writeAttribute("alpha", QString::number(pProperties->overwriteTransparency()));
m_pOutStream->writeEndElement(); // Color
m_pOutStream->writeEndElement(); // SurfaceAttributes
}
else if ((pProperties->renderingMode() == glc::OverwriteTransparencyAndMaterial))
{
GLC_Material* pMaterial= pProperties->overwriteMaterial();
m_pOutStream->writeStartElement("SurfaceAttributes");
m_pOutStream->writeAttribute("xsi:type", "SurfaceAttributesType");
m_pOutStream->writeStartElement("Color");
m_pOutStream->writeAttribute("xsi:type", "RGBAColorType");
m_pOutStream->writeAttribute("red", QString::number(pMaterial->diffuseColor().redF()));
m_pOutStream->writeAttribute("green", QString::number(pMaterial->diffuseColor().greenF()));
m_pOutStream->writeAttribute("blue", QString::number(pMaterial->diffuseColor().blueF()));
m_pOutStream->writeAttribute("alpha", QString::number(pProperties->overwriteTransparency()));
m_pOutStream->writeEndElement(); // Color
m_pOutStream->writeEndElement(); // SurfaceAttributes
}
else if ((pProperties->renderingMode() == glc::OverwriteMaterial))
{
GLC_Material* pMaterial= pProperties->overwriteMaterial();
m_pOutStream->writeStartElement("SurfaceAttributes");
m_pOutStream->writeAttribute("xsi:type", "SurfaceAttributesType");
m_pOutStream->writeStartElement("Color");
m_pOutStream->writeAttribute("xsi:type", "RGBAColorType");
m_pOutStream->writeAttribute("red", QString::number(pMaterial->diffuseColor().redF()));
m_pOutStream->writeAttribute("green", QString::number(pMaterial->diffuseColor().greenF()));
m_pOutStream->writeAttribute("blue", QString::number(pMaterial->diffuseColor().blueF()));
m_pOutStream->writeAttribute("alpha", QString::number(pMaterial->opacity()));
m_pOutStream->writeEndElement(); // Color
m_pOutStream->writeEndElement(); // SurfaceAttributes
}
}
m_pOutStream->writeEndElement(); // GraphicProperties
} }
m_pOutStream->writeEndElement(); // GraphicProperties
m_pOutStream->writeEndElement(); // DefaultViewProperty m_pOutStream->writeEndElement(); // DefaultViewProperty
} }
@ -1191,3 +1251,32 @@ bool GLC_WorldTo3dxml::continu()
} }
return continuValue; return continuValue;
} }
QString GLC_WorldTo3dxml::symplifyName(QString name)
{
const int nameSize= name.size();
for (int i= 0; i < nameSize; ++i)
{
if (!name.at(i).isLetterOrNumber() && (name.at(i) != '.'))
{
name.replace(i, 1, '_');
}
}
return name;
}
QList<unsigned int> GLC_WorldTo3dxml::instancePath(const GLC_StructOccurence* pOccurence)
{
QList<unsigned int> path;
if (!pOccurence->isOrphan())
{
GLC_StructInstance* pInstance= pOccurence->structInstance();
Q_ASSERT(m_InstanceToIdHash.contains(pInstance));
path.prepend(m_InstanceToIdHash.value(pInstance));
QList<unsigned int> subPath(instancePath(pOccurence->parent()));
subPath.append(path);
path= subPath;
}
return path;
}

View File

@ -166,7 +166,7 @@ private:
void addImageTextureTo3dxml(const QImage& image, const QString& fileName); void addImageTextureTo3dxml(const QImage& image, const QString& fileName);
//! Transform the given name to the 3DXML name (no double) //! Transform the given name to the 3DXML name (no double)
QString xmlFileName(const QString& fileName); QString xmlFileName(QString fileName);
//! Write extension attributes to 3DXML //! Write extension attributes to 3DXML
void writeExtensionAttributes(GLC_Attributes* pAttributes); void writeExtensionAttributes(GLC_Attributes* pAttributes);
@ -177,6 +177,12 @@ private:
//! return true if export must continu //! return true if export must continu
bool continu(); bool continu();
//! Return the simplified name of the given name
QString symplifyName(QString name);
//! Return the path of the given occurence
QList<unsigned int> instancePath(const GLC_StructOccurence* pOccurence);
//@} //@}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////

0
ground/openpilotgcs/src/libs/glc_lib/io/glc_xmlutil.h Normal file → Executable file
View File

View File

@ -27,6 +27,9 @@
#include <QtGlobal> #include <QtGlobal>
double glc::comparedPrecision= glc::defaultPrecision;
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
//Tools Functions //Tools Functions
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -520,12 +523,112 @@ bool glc::lineIntersectPlane(const GLC_Line3d& line, const GLC_Plane& plane, GLC
GLC_Point3d glc::project(const GLC_Point3d& point, const GLC_Line3d& line) GLC_Point3d glc::project(const GLC_Point3d& point, const GLC_Line3d& line)
{ {
// Create the plane from the point with normal define by the line direction const GLC_Vector3d lineDirection(line.direction().normalize());
const GLC_Plane plane(line.direction().normalize(), point); double t= lineDirection * (point - line.startingPoint());
GLC_Point3d intersection; GLC_Point3d projectedPoint= line.startingPoint() + (t * lineDirection);
const bool intersect= lineIntersectPlane(line, plane, &intersection); return projectedPoint;
Q_ASSERT(intersect == true);
return intersection;
} }
double glc::pointLineDistance(const GLC_Point3d& point, const GLC_Line3d& line)
{
const GLC_Vector3d lineDirection(line.direction().normalize());
double t= lineDirection * (point - line.startingPoint());
GLC_Point3d projectedPoint= line.startingPoint() + (t * lineDirection);
return (point - projectedPoint).length();
}
bool glc::pointsAreCollinear(const GLC_Point3d& p1, const GLC_Point3d& p2, const GLC_Point3d& p3)
{
bool subject= false;
if (compare(p1, p2) || compare(p1, p3) || compare(p2, p3))
{
subject= true;
}
else
{
GLC_Vector3d p1p2= (p2 - p1).setLength(1.0);
GLC_Vector3d p2p3= (p3 - p2).setLength(1.0);
subject= (compare(p1p2, p2p3) || compare(p1p2, p2p3.inverted()));
}
return subject;
}
bool glc::compare(double p1, double p2)
{
return qAbs(p1 - p2) <= comparedPrecision;
}
bool glc::compareAngle(double p1, double p2)
{
const double anglePrecision= toRadian(comparedPrecision);
return qAbs(p1 - p2) <= anglePrecision;
}
bool glc::compare(const GLC_Vector3d& v1, const GLC_Vector3d& v2)
{
bool compareResult= (qAbs(v1.x() - v2.x()) <= comparedPrecision);
compareResult= compareResult && (qAbs(v1.y() - v2.y()) <= comparedPrecision);
compareResult= compareResult && (qAbs(v1.z() - v2.z()) <= comparedPrecision);
return compareResult;
}
bool glc::compare(const GLC_Vector2d& v1, const GLC_Vector2d& v2)
{
bool compareResult= (qAbs(v1.getX() - v2.getX()) <= comparedPrecision);
return compareResult && (qAbs(v1.getY() - v2.getY()) <= comparedPrecision);
}
bool glc::compare(const QPointF& v1, const QPointF& v2)
{
bool compareResult= (qAbs(v1.x() - v2.x()) <= comparedPrecision);
return compareResult && (qAbs(v1.y() - v2.y()) <= comparedPrecision);
}
bool glc::pointInPolygon(const GLC_Point2d& point, const QList<GLC_Point2d>& polygon)
{
const int polygonSize= polygon.size();
bool inside= false;
int i= 0;
int j= polygonSize - 1;
while (i < polygonSize)
{
const GLC_Point2d point0= polygon.at(i);
const GLC_Point2d point1= polygon.at(j);
if (point.getY() < point1.getY())
{
//point1 above ray
if (point0.getY() <= point.getY())
{
//point2 on or below ray
const double val1= (point.getY() - point0.getY()) * (point1.getX() - point0.getX());
const double val2= (point.getX() - point0.getX()) * (point1.getY() - point0.getY());
if (val1 > val2) inside= !inside;
}
}
else if (point.getY() < point0.getY())
{
// point 1 on or below ray, point0 above ray
const double val1= (point.getY() - point0.getY()) * (point1.getX() - point0.getX());
const double val2= (point.getX() - point0.getX()) * (point1.getY() - point0.getY());
if (val1 < val2) inside= !inside;
}
j= i;
++i;
}
return inside;
}
double glc::zeroTo2PIAngle(double angle)
{
if (qFuzzyCompare(fabs(angle), glc::PI))
{
angle= glc::PI;
}
else if (angle < 0)
{
angle= (2.0 * glc::PI) + angle;
}
return angle;
}

View File

@ -27,6 +27,8 @@
#include <QVector> #include <QVector>
#include <QList> #include <QList>
#include <QPointF>
#include "glc_vector3d.h" #include "glc_vector3d.h"
#include "glc_line3d.h" #include "glc_line3d.h"
#include "glc_plane.h" #include "glc_plane.h"
@ -37,7 +39,8 @@
namespace glc namespace glc
{ {
const double defaultPrecision= 0.01;
extern double comparedPrecision;
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
/*! \name Tools Functions*/ /*! \name Tools Functions*/
//@{ //@{
@ -94,10 +97,33 @@ namespace glc
//! Return the midpoint of the two given points //! Return the midpoint of the two given points
inline GLC_Point3d midPoint(const GLC_Point3d& point1, const GLC_Point3d point2) inline GLC_Point3d midPoint(const GLC_Point3d& point1, const GLC_Point3d point2)
{ {return point1 + (point2 - point1) * 0.5;}
return point1 + (point2 - point1) * 0.5;
}
//! Return the perpendicular 2D vector of the given 2D vector
inline GLC_Vector2d perpVector(const GLC_Vector2d& vect)
{return GLC_Vector2d(-vect.getY(), vect.getX());}
//! Return the distance between the given point and line
GLC_LIB_EXPORT double pointLineDistance(const GLC_Point3d& point, const GLC_Line3d& line);
//! Return true if the given 3 points are collinear
GLC_LIB_EXPORT bool pointsAreCollinear(const GLC_Point3d& p1, const GLC_Point3d& p2, const GLC_Point3d& p3);
GLC_LIB_EXPORT bool compare(double p1, double p2);
GLC_LIB_EXPORT bool compareAngle(double p1, double p2);
GLC_LIB_EXPORT bool compare(const GLC_Vector3d& v1, const GLC_Vector3d& v2);
GLC_LIB_EXPORT bool compare(const GLC_Vector2d& v1, const GLC_Vector2d& v2);
GLC_LIB_EXPORT bool compare(const QPointF& v1, const QPointF& v2);
//! Return true if the given 2d point is inside the given polygon
GLC_LIB_EXPORT bool pointInPolygon(const GLC_Point2d& point, const QList<GLC_Point2d>& polygon);
//! Return the angle from 0 to 2PI from an given angle from -PI to PI
GLC_LIB_EXPORT double zeroTo2PIAngle(double angle);
//@} //@}

View File

@ -25,121 +25,99 @@
#include "glc_interpolator.h" #include "glc_interpolator.h"
using namespace glc; using namespace glc;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
// Contructeur par défaut Interpolation Linéaire
GLC_Interpolator::GLC_Interpolator() GLC_Interpolator::GLC_Interpolator()
: m_InterpolType(INTERPOL_LINEAIRE) : m_InterpolType(INTERPOL_LINEAIRE)
, m_nNbrPas(1) , m_StepCount(1)
{ {
} }
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Fonction Set // Set Function
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Défini la matrice d'interpolation
void GLC_Interpolator::SetInterpolMat(int NbrPas, const GLC_Vector3d &VectDepart, const GLC_Vector3d &VectArrive void GLC_Interpolator::SetInterpolMat(int NbrPas, const GLC_Vector3d &VectDepart, const GLC_Vector3d &VectArrive
, INTERPOL_TYPE Interpolation) , INTERPOL_TYPE Interpolation)
{ {
// Mise à jour des données membre
m_InterpolType= Interpolation; m_InterpolType= Interpolation;
if (!NbrPas) if (NbrPas != 0)
{ m_StepCount= NbrPas;
//TRACE("GLC_Interpolator::SetInterpolMat -> NbrPas == 0 \n");
} m_StartPoint= VectDepart;
else m_nNbrPas= NbrPas; m_EndPoint= VectArrive;
m_VectDepart= VectDepart;
m_VectArrive= VectArrive;
// Calcul de la matrice d'interpolation
CalcInterpolMat(); CalcInterpolMat();
} }
// Type d'interpolation
void GLC_Interpolator::SetType(INTERPOL_TYPE Interpolation) void GLC_Interpolator::SetType(INTERPOL_TYPE Interpolation)
{ {
if (m_InterpolType != Interpolation) if (m_InterpolType != Interpolation)
{ {
m_InterpolType= Interpolation; m_InterpolType= Interpolation;
// Calcul de la matrice d'interpolation
CalcInterpolMat(); CalcInterpolMat();
} }
} }
// Nombre de pas
void GLC_Interpolator::SetNbrPas(int NbrPas) void GLC_Interpolator::SetNbrPas(int NbrPas)
{ {
if (!NbrPas)
{
//TRACE("GLC_Interpolator::SetNbrPas -> NbrPas == 0 \n");
return;
}
if (m_nNbrPas != NbrPas) if ((NbrPas != 0) && (m_StepCount != NbrPas))
{ {
m_nNbrPas= NbrPas; m_StepCount= NbrPas;
// Calcul de la matrice d'interpolation
CalcInterpolMat(); CalcInterpolMat();
} }
} }
// Vecteur d'arrivée et de depart
void GLC_Interpolator::SetVecteurs(const GLC_Vector3d &VectDepart, const GLC_Vector3d &VectArrive) void GLC_Interpolator::SetVecteurs(const GLC_Vector3d &VectDepart, const GLC_Vector3d &VectArrive)
{ {
m_VectDepart= VectDepart; m_StartPoint= VectDepart;
m_VectArrive= VectArrive; m_EndPoint= VectArrive;
// Calcul de la matrice d'interpolation
CalcInterpolMat(); CalcInterpolMat();
} }
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Fonction Get // Private sevices functions
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// Fonctions de Service privée
//////////////////////////////////////////////////////////////////////
// Calcul La matrice d'interpolation
bool GLC_Interpolator::CalcInterpolMat(void) bool GLC_Interpolator::CalcInterpolMat(void)
{ {
// Verifie que les vecteur d'arrivé et de départ sont différent
if (m_VectDepart == m_VectArrive) if (m_StartPoint != m_EndPoint)
{ {
//TRACE("GLC_Interpolator::CalcInterpolMat : Depart == Arrive\n"); switch (m_InterpolType)
return false; {
case INTERPOL_LINEAIRE:
return CalcInterpolLineaireMat();
break;
case INTERPOL_ANGULAIRE:
return CalcInterpolAngulaireMat();
break;
case INTERPOL_HOMOTETIE:
return false;
break;
default:
return false;
}
} }
else return false;
switch (m_InterpolType)
{
case INTERPOL_LINEAIRE:
return CalcInterpolLineaireMat();
break;
case INTERPOL_ANGULAIRE:
return CalcInterpolAngulaireMat();
break;
case INTERPOL_HOMOTETIE:
return false;
break;
default:
//TRACE("GLC_Interpolator::CalcInterpolMat : Type d'interpolation non valide\n");
return false;
}
} }
// Calcul la matrice d'interpolation linéaire
bool GLC_Interpolator::CalcInterpolLineaireMat(void) bool GLC_Interpolator::CalcInterpolLineaireMat(void)
{ {
// Calcul la matrice de translation const GLC_Vector3d VectTrans= (m_EndPoint - m_StartPoint) * (1.0 / m_StepCount);
const GLC_Vector3d VectTrans= (m_VectArrive - m_VectDepart) * (1.0 / m_nNbrPas);
if(VectTrans.isNull()) if(VectTrans.isNull())
{ {
//TRACE("GLC_Interpolator::CalcInterpolLineaireMat -> Translation NULL\n");
m_InterpolMat.setToIdentity(); m_InterpolMat.setToIdentity();
return false; return false;
} }
@ -150,17 +128,15 @@ bool GLC_Interpolator::CalcInterpolLineaireMat(void)
} }
} }
// Calcul la matrice d'interpolation angulaire
bool GLC_Interpolator::CalcInterpolAngulaireMat(void) bool GLC_Interpolator::CalcInterpolAngulaireMat(void)
{ {
// Calcul de l'axe de rotation
const GLC_Vector3d AxeRot(m_VectDepart ^ m_VectArrive); const GLC_Vector3d AxeRot(m_StartPoint ^ m_EndPoint);
// Calcul de l'angle entre les vecteurs
const double Angle= m_VectArrive.angleWithVect(m_VectDepart) / m_nNbrPas; const double Angle= m_EndPoint.angleWithVect(m_StartPoint) / m_StepCount;
// Calcul de la matrice de rotation
if (qFuzzyCompare(Angle, 0.0)) if (qFuzzyCompare(Angle, 0.0))
{ {
//TRACE("GLC_Interpolator::CalcInterpolAngulaireMat -> Rotation NULL\n");
m_InterpolMat.setToIdentity(); m_InterpolMat.setToIdentity();
return false; return false;
} }

View File

@ -47,66 +47,65 @@ enum INTERPOL_TYPE
class GLC_LIB_EXPORT GLC_Interpolator class GLC_LIB_EXPORT GLC_Interpolator
{ {
//////////////////////////////////////////////////////////////////////
// Construction
//////////////////////////////////////////////////////////////////////
public: public:
// Contructeur par défaut Interpolation Linéaire //! Default linear interpolation constructor
GLC_Interpolator(); GLC_Interpolator();
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Fonctions Set // Set Function
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
public: public:
// Défini la matrice d'interpolation //! Set interpolation matrix
void SetInterpolMat(int NbrPas, const GLC_Vector3d &VectDepart, const GLC_Vector3d &VectArrive void SetInterpolMat(int NbrPas, const GLC_Vector3d &VectDepart, const GLC_Vector3d &VectArrive
, INTERPOL_TYPE Interpolation = INTERPOL_LINEAIRE); , INTERPOL_TYPE Interpolation = INTERPOL_LINEAIRE);
// Type d'interpolation
//! Set interpolation type
void SetType(INTERPOL_TYPE Interpolation); void SetType(INTERPOL_TYPE Interpolation);
// Nombre de pas
// Number of step
void SetNbrPas(int NbrPas); void SetNbrPas(int NbrPas);
// Vecteur d'arrivée et de depart
//! Set start and end vector
void SetVecteurs(const GLC_Vector3d &VectDepart, const GLC_Vector3d &VectArrive); void SetVecteurs(const GLC_Vector3d &VectDepart, const GLC_Vector3d &VectArrive);
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Fonctions Get // Get Function
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
public: public:
// Retourne la matrice d'interpolation //! Return th interpolation matrix
GLC_Matrix4x4 GetInterpolMat(void) const inline GLC_Matrix4x4 GetInterpolMat(void) const
{ {return m_InterpolMat;}
return m_InterpolMat;
}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Fonctions de Service privée // Private services functions
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
private: private:
// Calcul La matrice d'interpolation //! Compute interpolation matrix
bool CalcInterpolMat(void); bool CalcInterpolMat(void);
// Calcul la matrice d'interpolation linéaire //! Compute linear interolation matrix
bool CalcInterpolLineaireMat(void); bool CalcInterpolLineaireMat(void);
// Calcul la matrice d'interpolation angulaire //! Compute angular interpolation matrix
bool CalcInterpolAngulaireMat(void); bool CalcInterpolAngulaireMat(void);
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Membres privés // Membres privés
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
private: private:
// Vecteur de départ //! Start Point
GLC_Vector3d m_VectDepart; GLC_Point3d m_StartPoint;
// Vecteur d'arriver
GLC_Vector3d m_VectArrive;
// Type d'interpolation courante //! End Point
GLC_Point3d m_EndPoint;
//! Interpolation type
INTERPOL_TYPE m_InterpolType; INTERPOL_TYPE m_InterpolType;
// Nombre de pas d'interpolation //! Interpolation step count
int m_nNbrPas; int m_StepCount;
// Matrice d'interpolation //! Interpolation matrix
GLC_Matrix4x4 m_InterpolMat; GLC_Matrix4x4 m_InterpolMat;
}; };

View File

@ -26,7 +26,7 @@
#include "glc_vector3d.h" #include "glc_vector3d.h"
#include "glc_config.h" #include "../glc_config.h"
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
//! \class GLC_Line3d //! \class GLC_Line3d

View File

@ -278,17 +278,6 @@ the matrix :
}; };
//! Return the determinant of the given Matrix 3X3
inline double getDeterminant3x3(const double *Mat3x3)
{
double Determinant;
Determinant= Mat3x3[0] * ( Mat3x3[4] * Mat3x3[8] - Mat3x3[7] * Mat3x3[5]);
Determinant+= - Mat3x3[3] * ( Mat3x3[1] * Mat3x3[8] - Mat3x3[7] * Mat3x3[2]);
Determinant+= Mat3x3[6] * ( Mat3x3[1] * Mat3x3[5] - Mat3x3[4] * Mat3x3[2]);
return Determinant;
}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Constructor/Destructor // Constructor/Destructor

View File

@ -26,10 +26,12 @@
#define GLC_VECTOR2D_H_ #define GLC_VECTOR2D_H_
#include <QString> #include <QString>
#include <QPointF>
#include "glc_utils_maths.h" #include "glc_utils_maths.h"
#include "glc_vector2df.h" #include "glc_vector2df.h"
#include "glc_config.h" #include "../glc_config.h"
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// definition global // definition global
@ -51,7 +53,7 @@ class GLC_LIB_EXPORT GLC_Vector2d
/*! Overload unary "-" operator*/ /*! Overload unary "-" operator*/
inline friend GLC_Vector2d operator - (const GLC_Vector2d &Vect) inline friend GLC_Vector2d operator - (const GLC_Vector2d &Vect)
{ {
return GLC_Vector2d(-Vect.dVecteur[0], -Vect.dVecteur[1]); return GLC_Vector2d(-Vect.m_Vector[0], -Vect.m_Vector[1]);
} }
@ -67,15 +69,15 @@ public:
*/ */
inline GLC_Vector2d() inline GLC_Vector2d()
{ {
dVecteur[0]= 0.0; m_Vector[0]= 0.0;
dVecteur[1]= 0.0; m_Vector[1]= 0.0;
} }
/*! Standard constructor With x, y = 0.0*/ /*! Standard constructor With x, y = 0.0*/
inline GLC_Vector2d(const double &dX, const double &dY) inline GLC_Vector2d(const double &dX, const double &dY)
{ {
dVecteur[0]= dX; m_Vector[0]= dX;
dVecteur[1]= dY; m_Vector[1]= dY;
} }
/*! Recopy constructor /*! Recopy constructor
@ -86,9 +88,14 @@ public:
*/ */
inline GLC_Vector2d(const GLC_Vector2d &Vect) inline GLC_Vector2d(const GLC_Vector2d &Vect)
{ {
dVecteur[0]= Vect.dVecteur[0]; m_Vector[0]= Vect.m_Vector[0];
dVecteur[1]= Vect.dVecteur[1]; m_Vector[1]= Vect.m_Vector[1];
} }
//! Return the QPointF of this GLC_Vector
inline QPointF toQPointF() const
{return QPointF(m_Vector[0], m_Vector[1]);}
//@} //@}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
/*! @name Operator Overload */ /*! @name Operator Overload */
@ -99,7 +106,7 @@ public:
/*! Overload binary "+" operator*/ /*! Overload binary "+" operator*/
inline GLC_Vector2d operator + (const GLC_Vector2d &Vect) const inline GLC_Vector2d operator + (const GLC_Vector2d &Vect) const
{ {
GLC_Vector2d VectResult(dVecteur[0] + Vect.dVecteur[0], dVecteur[1] + Vect.dVecteur[1]); GLC_Vector2d VectResult(m_Vector[0] + Vect.m_Vector[0], m_Vector[1] + Vect.m_Vector[1]);
return VectResult; return VectResult;
} }
@ -107,8 +114,8 @@ public:
/*! Overload "=" operator*/ /*! Overload "=" operator*/
inline GLC_Vector2d& operator = (const GLC_Vector2d &Vect) inline GLC_Vector2d& operator = (const GLC_Vector2d &Vect)
{ {
dVecteur[0]= Vect.dVecteur[0]; m_Vector[0]= Vect.m_Vector[0];
dVecteur[1]= Vect.dVecteur[1]; m_Vector[1]= Vect.m_Vector[1];
return *this; return *this;
} }
@ -116,8 +123,8 @@ public:
/*! Overload "=" operator*/ /*! Overload "=" operator*/
inline GLC_Vector2d& operator = (const GLC_Vector2df &Vect) inline GLC_Vector2d& operator = (const GLC_Vector2df &Vect)
{ {
dVecteur[0]= static_cast<double>(Vect.vector[0]); m_Vector[0]= static_cast<double>(Vect.vector[0]);
dVecteur[1]= static_cast<double>(Vect.vector[1]); m_Vector[1]= static_cast<double>(Vect.vector[1]);
return *this; return *this;
} }
@ -134,7 +141,7 @@ public:
/*! Overload binary "-" operator*/ /*! Overload binary "-" operator*/
inline GLC_Vector2d operator - (const GLC_Vector2d &Vect) const inline GLC_Vector2d operator - (const GLC_Vector2d &Vect) const
{ {
GLC_Vector2d VectResult(dVecteur[0] - Vect.dVecteur[0], dVecteur[1] - Vect.dVecteur[1]); GLC_Vector2d VectResult(m_Vector[0] - Vect.m_Vector[0], m_Vector[1] - Vect.m_Vector[1]);
return VectResult; return VectResult;
} }
@ -149,27 +156,27 @@ public:
/*! Overload dot product "^" operator*/ /*! Overload dot product "^" operator*/
inline double operator ^ (const GLC_Vector2d &Vect) const inline double operator ^ (const GLC_Vector2d &Vect) const
{ {
return dVecteur[0] * Vect.dVecteur[1] - dVecteur[1] * Vect.dVecteur[0]; return m_Vector[0] * Vect.m_Vector[1] - m_Vector[1] * Vect.m_Vector[0];
} }
/*! Overload scalar product "*" operator between 2 vector*/ /*! Overload scalar product "*" operator between 2 vector*/
inline double operator * (const GLC_Vector2d &Vect) const inline double operator * (const GLC_Vector2d &Vect) const
{ {
return dVecteur[0] * Vect.dVecteur[0] + dVecteur[1] * Vect.dVecteur[1]; return m_Vector[0] * Vect.m_Vector[0] + m_Vector[1] * Vect.m_Vector[1];
} }
/*! Overload scalar product "*" operator between 1 vector and one scalar*/ /*! Overload scalar product "*" operator between 1 vector and one scalar*/
inline GLC_Vector2d operator * (double Scalaire) const inline GLC_Vector2d operator * (double Scalaire) const
{ {
return GLC_Vector2d(dVecteur[0] * Scalaire, dVecteur[1] * Scalaire);; return GLC_Vector2d(m_Vector[0] * Scalaire, m_Vector[1] * Scalaire);;
} }
/*! Overload equality "==" operator*/ /*! Overload equality "==" operator*/
inline bool operator == (const GLC_Vector2d &Vect) const inline bool operator == (const GLC_Vector2d &Vect) const
{ {
bool bResult= qFuzzyCompare(dVecteur[0], Vect.dVecteur[0]); bool bResult= qFuzzyCompare(m_Vector[0], Vect.m_Vector[0]);
bResult= bResult && qFuzzyCompare(dVecteur[1], Vect.dVecteur[1]); bResult= bResult && qFuzzyCompare(m_Vector[1], Vect.m_Vector[1]);
return bResult; return bResult;
} }
@ -190,33 +197,40 @@ public:
/*! X Composante*/ /*! X Composante*/
inline GLC_Vector2d& setX(const double &dX) inline GLC_Vector2d& setX(const double &dX)
{ {
dVecteur[0]= dX; m_Vector[0]= dX;
return *this; return *this;
} }
/*! Y Composante*/ /*! Y Composante*/
inline GLC_Vector2d& setY(const double &dY) inline GLC_Vector2d& setY(const double &dY)
{ {
dVecteur[1]= dY; m_Vector[1]= dY;
return *this; return *this;
} }
/*! All Composante*/ /*! All Composante*/
inline GLC_Vector2d& setVect(const double &dX, const double &dY) inline GLC_Vector2d& setVect(const double &dX, const double &dY)
{ {
dVecteur[0]= dX; m_Vector[0]= dX;
dVecteur[1]= dY; m_Vector[1]= dY;
return *this; return *this;
} }
/*! From another Vector*/ /*! From another Vector*/
inline GLC_Vector2d& setVect(const GLC_Vector2d &Vect) inline GLC_Vector2d& setVect(const GLC_Vector2d &Vect)
{ {
dVecteur[0]= Vect.dVecteur[0]; m_Vector[0]= Vect.m_Vector[0];
dVecteur[1]= Vect.dVecteur[1]; m_Vector[1]= Vect.m_Vector[1];
return *this; return *this;
} }
//! Set vector lenght from the given scalar and return a reference of this vector
inline GLC_Vector2d& setLength(double);
//! Normalize this vector and return a reference to it
inline GLC_Vector2d& normalize()
{return setLength(1.0);}
//@} //@}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -227,32 +241,32 @@ public:
/*! X Composante*/ /*! X Composante*/
inline double getX(void) const inline double getX(void) const
{ {
return dVecteur[0]; return m_Vector[0];
} }
/*! Y Composante*/ /*! Y Composante*/
inline double getY(void) const inline double getY(void) const
{ {
return dVecteur[1]; return m_Vector[1];
} }
/*! retourne un pointeur constant vers le tableau du vecteur.*/ /*! retourne un pointeur constant vers le tableau du vecteur.*/
inline const double *return_dVect(void) const inline const double *return_dVect(void) const
{ {
return dVecteur; return m_Vector;
} }
/*! Return true if the vector is null*/ /*! Return true if the vector is null*/
inline bool isNull(void) const inline bool isNull(void) const
{ {
return qFuzzyCompare(dVecteur[0], 0.0) && qFuzzyCompare(dVecteur[1], 0.0); return qFuzzyCompare(m_Vector[0], 0.0) && qFuzzyCompare(m_Vector[1], 0.0);
} }
//! return the string representation of vector //! return the string representation of vector
inline QString toString() const inline QString toString() const
{ {
return QString("[") + QString::number(dVecteur[0]) + QString(" , ") + QString::number(dVecteur[1]) + QString("]"); return QString("[") + QString::number(m_Vector[0]) + QString(" , ") + QString::number(m_Vector[1]) + QString("]");
} }
//! return a vector perpendicular to this //! return a vector perpendicular to this
inline GLC_Vector2d perp() const inline GLC_Vector2d perp() const
{ {
return GLC_Vector2d(-dVecteur[1], dVecteur[0]); return GLC_Vector2d(-m_Vector[1], m_Vector[0]);
} }
//@} //@}
@ -264,11 +278,25 @@ private:
* vector[0] X \n * vector[0] X \n
* vector[1] Y \n * vector[1] Y \n
*/ */
double dVecteur[2]; double m_Vector[2];
}; //class GLC_Vector2d }; //class GLC_Vector2d
//! Define GLC_Point2D //! Define GLC_Point2D
typedef GLC_Vector2d GLC_Point2d; typedef GLC_Vector2d GLC_Point2d;
inline GLC_Vector2d& GLC_Vector2d::setLength(double norme)
{
const double normCur= sqrt( m_Vector[0] * m_Vector[0] + m_Vector[1] * m_Vector[1]);
if (normCur != 0.0f)
{
const double Coef = norme / normCur;
m_Vector[0] = m_Vector[0] * Coef;
m_Vector[1] = m_Vector[1] * Coef;
}
return *this;
}
#endif /*GLC_VECTOR2D_H_*/ #endif /*GLC_VECTOR2D_H_*/

View File

@ -76,6 +76,9 @@ public:
//! Construct a 3d vector from another 3d float vector //! Construct a 3d vector from another 3d float vector
inline GLC_Vector3d(const GLC_Vector3df &vector); inline GLC_Vector3d(const GLC_Vector3df &vector);
//! Construct a 3d vector from a 2d float vector
inline GLC_Vector3d(const GLC_Vector2d &vector);
//@} //@}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -111,9 +114,12 @@ public:
/*! retrieve component corresponding to mask vector NULL component*/ /*! retrieve component corresponding to mask vector NULL component*/
inline GLC_Vector2d toVector2d(const GLC_Vector3d& mask) const; inline GLC_Vector2d toVector2d(const GLC_Vector3d& mask) const;
//! Return the Angle from this vector to the given vector //! Return the Angle from this vector to the given vector (from 0 to PI)
inline double angleWithVect(GLC_Vector3d Vect) const; inline double angleWithVect(GLC_Vector3d Vect) const;
//! Return the signed angle from this vector to th given vector with the given direction (from 0 to -PI and 0 to PI)
inline double signedAngleWithVect(GLC_Vector3d Vect, const GLC_Vector3d& dir) const;
//! Return the float 3D vector from this vector //! Return the float 3D vector from this vector
inline GLC_Vector3df toVector3df() const inline GLC_Vector3df toVector3df() const
{return GLC_Vector3df(static_cast<float>(m_Vector[0]), static_cast<float>(m_Vector[1]), static_cast<float>(m_Vector[2]));} {return GLC_Vector3df(static_cast<float>(m_Vector[0]), static_cast<float>(m_Vector[1]), static_cast<float>(m_Vector[2]));}
@ -289,6 +295,18 @@ inline QDataStream &operator>>(QDataStream &stream, GLC_Vector3d &vector)
return stream; return stream;
} }
//! Return the determinant of the given Matrix 3X3
inline double getDeterminant3x3(const double *Mat3x3)
{
double Determinant;
Determinant= Mat3x3[0] * ( Mat3x3[4] * Mat3x3[8] - Mat3x3[7] * Mat3x3[5]);
Determinant+= - Mat3x3[3] * ( Mat3x3[1] * Mat3x3[8] - Mat3x3[7] * Mat3x3[2]);
Determinant+= Mat3x3[6] * ( Mat3x3[1] * Mat3x3[5] - Mat3x3[4] * Mat3x3[2]);
return Determinant;
}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// inline method implementation // inline method implementation
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -314,6 +332,13 @@ GLC_Vector3d::GLC_Vector3d(const GLC_Vector3df &vector)
m_Vector[2]= static_cast<double>(vector.m_Vector[2]); m_Vector[2]= static_cast<double>(vector.m_Vector[2]);
} }
GLC_Vector3d::GLC_Vector3d(const GLC_Vector2d &vector)
{
m_Vector[0]= vector.getX();
m_Vector[1]= vector.getY();
m_Vector[2]= 0.0;
}
GLC_Vector3d& GLC_Vector3d::operator = (const GLC_Vector3df &Vect) GLC_Vector3d& GLC_Vector3d::operator = (const GLC_Vector3df &Vect)
{ {
m_Vector[0]= static_cast<double>(Vect.m_Vector[0]); m_Vector[0]= static_cast<double>(Vect.m_Vector[0]);
@ -419,6 +444,48 @@ double GLC_Vector3d::angleWithVect(GLC_Vector3d Vect) const
else return 0.0; else return 0.0;
} }
double GLC_Vector3d::signedAngleWithVect(GLC_Vector3d Vect, const GLC_Vector3d& dir) const
{
double angle= 0.0;
GLC_Vector3d ThisVect(*this);
ThisVect.normalize();
Vect.normalize();
if (Vect == ThisVect.inverted())
{
angle= glc::PI;
}
else if (Vect != ThisVect)
{
// Rotation axis
const GLC_Vector3d VectAxeRot(ThisVect ^ Vect);
// Check if the rotation axis vector is null
if (!VectAxeRot.isNull())
{
double mat3x3[9];
mat3x3[0]= ThisVect.m_Vector[0];
mat3x3[1]= ThisVect.m_Vector[1];
mat3x3[2]= ThisVect.m_Vector[2];
mat3x3[3]= Vect.m_Vector[0];
mat3x3[4]= Vect.m_Vector[1];
mat3x3[5]= Vect.m_Vector[2];
mat3x3[6]= dir.m_Vector[0];
mat3x3[7]= dir.m_Vector[1];
mat3x3[8]= dir.m_Vector[2];
double det= getDeterminant3x3(mat3x3);
double sign= 1.0;
if (det != 0) sign= fabs(det) / det;
angle= acos(ThisVect * Vect) * sign;
}
}
return angle;
}
QString GLC_Vector3d::toString() const QString GLC_Vector3d::toString() const
{ {
QString result("["); QString result("[");

View File

@ -110,8 +110,8 @@ public:
//! Copy from an GLC_Vector3d //! Copy from an GLC_Vector3d
inline GLC_Vector4d(const GLC_Vector2d &Vect) inline GLC_Vector4d(const GLC_Vector2d &Vect)
{ {
vector[0]= Vect.dVecteur[0]; vector[0]= Vect.m_Vector[0];
vector[1]= Vect.dVecteur[1]; vector[1]= Vect.m_Vector[1];
vector[2]= 0.0; vector[2]= 0.0;
vector[3]= 1.0; vector[3]= 1.0;
} }
@ -168,8 +168,8 @@ public:
//! Overload "=" operator //! Overload "=" operator
inline GLC_Vector4d& operator = (const GLC_Vector2d &Vect) inline GLC_Vector4d& operator = (const GLC_Vector2d &Vect)
{ {
vector[0]= Vect.dVecteur[0]; vector[0]= Vect.m_Vector[0];
vector[1]= Vect.dVecteur[1]; vector[1]= Vect.m_Vector[1];
vector[2]= 0.0; vector[2]= 0.0;
vector[3]= 1.0; vector[3]= 1.0;

View File

@ -40,7 +40,6 @@
GLC_3DViewCollection::GLC_3DViewCollection() GLC_3DViewCollection::GLC_3DViewCollection()
: m_3DViewInstanceHash() : m_3DViewInstanceHash()
, m_pBoundingBox(NULL)
, m_SelectedInstances() , m_SelectedInstances()
, m_ShadedPointerViewInstanceHash() , m_ShadedPointerViewInstanceHash()
, m_ShaderGroup() , m_ShaderGroup()
@ -50,6 +49,7 @@ GLC_3DViewCollection::GLC_3DViewCollection()
, m_pViewport(NULL) , m_pViewport(NULL)
, m_pSpacePartitioning(NULL) , m_pSpacePartitioning(NULL)
, m_UseSpacePartitioning(false) , m_UseSpacePartitioning(false)
, m_IsViewable(true)
{ {
} }
@ -62,7 +62,7 @@ GLC_3DViewCollection::~GLC_3DViewCollection()
// Set Functions // Set Functions
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
bool GLC_3DViewCollection::bindShader(GLuint shaderId) bool GLC_3DViewCollection::bindShader(GLC_uint shaderId)
{ {
if (m_ShadedPointerViewInstanceHash.contains(shaderId)) if (m_ShadedPointerViewInstanceHash.contains(shaderId))
{ {
@ -76,7 +76,7 @@ bool GLC_3DViewCollection::bindShader(GLuint shaderId)
} }
} }
bool GLC_3DViewCollection::unBindShader(GLuint shaderId) bool GLC_3DViewCollection::unBindShader(GLC_uint shaderId)
{ {
bool result= false; bool result= false;
if (m_ShadedPointerViewInstanceHash.contains(shaderId)) if (m_ShadedPointerViewInstanceHash.contains(shaderId))
@ -127,7 +127,7 @@ bool GLC_3DViewCollection::unBindAllShader()
return result; return result;
} }
bool GLC_3DViewCollection::add(const GLC_3DViewInstance& node, GLuint shaderID) bool GLC_3DViewCollection::add(const GLC_3DViewInstance& node, GLC_uint shaderID)
{ {
bool result= false; bool result= false;
const GLC_uint key= node.id(); const GLC_uint key= node.id();
@ -170,19 +170,10 @@ bool GLC_3DViewCollection::add(const GLC_3DViewInstance& node, GLuint shaderID)
result=true; result=true;
} }
if(result)
{
// Bounding box validity
if (NULL != m_pBoundingBox)
{
delete m_pBoundingBox;
m_pBoundingBox= NULL;
}
}
return result; return result;
} }
void GLC_3DViewCollection::changeShadingGroup(GLC_uint instanceId, GLuint shaderId) void GLC_3DViewCollection::changeShadingGroup(GLC_uint instanceId, GLC_uint shaderId)
{ {
// Test if the specified instance exist // Test if the specified instance exist
Q_ASSERT(m_3DViewInstanceHash.contains(instanceId)); Q_ASSERT(m_3DViewInstanceHash.contains(instanceId));
@ -254,13 +245,6 @@ bool GLC_3DViewCollection::remove(GLC_uint Key)
m_3DViewInstanceHash.remove(Key); // Delete the conteneur m_3DViewInstanceHash.remove(Key); // Delete the conteneur
// Bounding box validity
if (NULL != m_pBoundingBox)
{
delete m_pBoundingBox;
m_pBoundingBox= NULL;
}
//qDebug("GLC_3DViewCollection::removeNode : Element succesfuly deleted"); //qDebug("GLC_3DViewCollection::removeNode : Element succesfuly deleted");
return true; return true;
@ -293,13 +277,6 @@ void GLC_3DViewCollection::clear(void)
// Clear main Hash table // Clear main Hash table
m_3DViewInstanceHash.clear(); m_3DViewInstanceHash.clear();
// delete the boundingBox
if (m_pBoundingBox != NULL)
{
delete m_pBoundingBox;
m_pBoundingBox= NULL;
}
// delete the space partitioning // delete the space partitioning
delete m_pSpacePartitioning; delete m_pSpacePartitioning;
} }
@ -438,12 +415,6 @@ void GLC_3DViewCollection::setVisibility(const GLC_uint key, const bool visibili
if (iNode != m_3DViewInstanceHash.end()) if (iNode != m_3DViewInstanceHash.end())
{ // Ok, the key exist { // Ok, the key exist
iNode.value().setVisibility(visibility); iNode.value().setVisibility(visibility);
// Bounding box validity
if (NULL != m_pBoundingBox)
{
delete m_pBoundingBox;
m_pBoundingBox= NULL;
}
} }
} }
@ -457,14 +428,6 @@ void GLC_3DViewCollection::showAll()
iEntry.value().setVisibility(true); iEntry.value().setVisibility(true);
iEntry++; iEntry++;
} }
// Bounding box validity
if (NULL != m_pBoundingBox)
{
delete m_pBoundingBox;
m_pBoundingBox= NULL;
}
} }
void GLC_3DViewCollection::hideAll() void GLC_3DViewCollection::hideAll()
@ -478,13 +441,6 @@ void GLC_3DViewCollection::hideAll()
iEntry++; iEntry++;
} }
// Bounding box validity
if (NULL != m_pBoundingBox)
{
delete m_pBoundingBox;
m_pBoundingBox= NULL;
}
} }
void GLC_3DViewCollection::bindSpacePartitioning(GLC_SpacePartitioning* pSpacePartitioning) void GLC_3DViewCollection::bindSpacePartitioning(GLC_SpacePartitioning* pSpacePartitioning)
@ -526,6 +482,17 @@ void GLC_3DViewCollection::updateInstanceViewableState(const GLC_Frustum& frustu
m_pSpacePartitioning->updateViewableInstances(frustum); m_pSpacePartitioning->updateViewableInstances(frustum);
} }
void GLC_3DViewCollection::setVboUsage(bool usage)
{
ViewInstancesHash::iterator iEntry= m_3DViewInstanceHash.begin();
while (iEntry != m_3DViewInstanceHash.constEnd())
{
iEntry.value().setVboUsage(usage);
iEntry++;
}
}
QList<GLC_3DViewInstance*> GLC_3DViewCollection::instancesHandle() QList<GLC_3DViewInstance*> GLC_3DViewCollection::instancesHandle()
{ {
QList<GLC_3DViewInstance*> instancesList; QList<GLC_3DViewInstance*> instancesList;
@ -583,48 +550,22 @@ GLC_3DViewInstance* GLC_3DViewCollection::instanceHandle(GLC_uint Key)
GLC_BoundingBox GLC_3DViewCollection::boundingBox(bool allObject) GLC_BoundingBox GLC_3DViewCollection::boundingBox(bool allObject)
{ {
// If the bounding box is not valid delete it GLC_BoundingBox boundingBox;
if (allObject)
{
delete m_pBoundingBox;
m_pBoundingBox= NULL;
}
else
{
setBoundingBoxValidity();
}
// Check if the bounding box have to be updated // Check if the bounding box have to be updated
if ((m_pBoundingBox == NULL) && !m_3DViewInstanceHash.isEmpty()) if (!m_3DViewInstanceHash.isEmpty())
{ {
// There is objects in the collection and the collection or bounding box is not valid
m_pBoundingBox= new GLC_BoundingBox();
ViewInstancesHash::iterator iEntry= m_3DViewInstanceHash.begin(); ViewInstancesHash::iterator iEntry= m_3DViewInstanceHash.begin();
while (iEntry != m_3DViewInstanceHash.constEnd()) while (iEntry != m_3DViewInstanceHash.constEnd())
{ {
if(allObject || iEntry.value().isVisible() == m_IsInShowSate) if(allObject || iEntry.value().isVisible() == m_IsInShowSate)
{ {
// Combine Collection BoundingBox with element Bounding Box // Combine Collection BoundingBox with element Bounding Box
m_pBoundingBox->combine(iEntry.value().boundingBox()); boundingBox.combine(iEntry.value().boundingBox());
} }
++iEntry; ++iEntry;
} }
} }
return boundingBox;
if (NULL == m_pBoundingBox) m_pBoundingBox= new GLC_BoundingBox;
if (allObject)
{
GLC_BoundingBox allBoundingBox(*m_pBoundingBox);
delete m_pBoundingBox;
m_pBoundingBox= NULL;
return allBoundingBox;
}
else
{
return *m_pBoundingBox;
}
} }
int GLC_3DViewCollection::drawableObjectsSize() const int GLC_3DViewCollection::drawableObjectsSize() const
@ -672,7 +613,7 @@ int GLC_3DViewCollection::numberOfUsedShadingGroup() const
void GLC_3DViewCollection::render(GLuint groupId, glc::RenderFlag renderFlag) void GLC_3DViewCollection::render(GLuint groupId, glc::RenderFlag renderFlag)
{ {
if (!isEmpty()) if (!isEmpty() && m_IsViewable)
{ {
if (renderFlag == glc::WireRenderFlag) if (renderFlag == glc::WireRenderFlag)
{ {
@ -682,12 +623,12 @@ void GLC_3DViewCollection::render(GLuint groupId, glc::RenderFlag renderFlag)
if (GLC_State::isInSelectionMode()) if (GLC_State::isInSelectionMode())
{ {
glDisable(GL_BLEND); glDisable(GL_BLEND);
glDisable(GL_LIGHTING); GLC_Context::current()->glcEnableLighting(false);
glDisable(GL_TEXTURE_2D); glDisable(GL_TEXTURE_2D);
} }
else else
{ {
glEnable(GL_LIGHTING); GLC_Context::current()->glcEnableLighting(true);
} }
glDraw(groupId, renderFlag); glDraw(groupId, renderFlag);
@ -699,12 +640,12 @@ void GLC_3DViewCollection::render(GLuint groupId, glc::RenderFlag renderFlag)
} }
void GLC_3DViewCollection::renderShaderGroup(glc::RenderFlag renderFlag) void GLC_3DViewCollection::renderShaderGroup(glc::RenderFlag renderFlag)
{ {
if (!isEmpty()) if (!isEmpty() && m_IsViewable)
{ {
if (GLC_State::isInSelectionMode()) if (GLC_State::isInSelectionMode())
{ {
glDisable(GL_BLEND); glDisable(GL_BLEND);
glDisable(GL_LIGHTING); GLC_Context::current()->glcEnableLighting(false);
glDisable(GL_TEXTURE_2D); glDisable(GL_TEXTURE_2D);
} }
@ -717,7 +658,7 @@ void GLC_3DViewCollection::renderShaderGroup(glc::RenderFlag renderFlag)
} }
} }
void GLC_3DViewCollection::glDraw(GLuint groupId, glc::RenderFlag renderFlag) void GLC_3DViewCollection::glDraw(GLC_uint groupId, glc::RenderFlag renderFlag)
{ {
// Set render Mode and OpenGL state // Set render Mode and OpenGL state
if (!GLC_State::isInSelectionMode() && (groupId == 0)) if (!GLC_State::isInSelectionMode() && (groupId == 0))
@ -773,30 +714,3 @@ void GLC_3DViewCollection::glDraw(GLuint groupId, glc::RenderFlag renderFlag)
glEnable(GL_DEPTH_TEST); glEnable(GL_DEPTH_TEST);
} }
} }
void GLC_3DViewCollection::setBoundingBoxValidity(void)
{
if (NULL != m_pBoundingBox)
{
if (!m_3DViewInstanceHash.isEmpty())
{
// Check instance bounding box validity
ViewInstancesHash::iterator iEntry= m_3DViewInstanceHash.begin();
while (iEntry != m_3DViewInstanceHash.constEnd())
{
if (!iEntry.value().boundingBoxValidity())
{
delete m_pBoundingBox;
m_pBoundingBox= NULL;
return;
}
iEntry++;
}
}
else if (!m_pBoundingBox->isEmpty())
{
delete m_pBoundingBox;
m_pBoundingBox= NULL;
}
}
}

View File

@ -45,10 +45,10 @@ typedef QHash< GLC_uint, GLC_3DViewInstance> ViewInstancesHash;
typedef QHash<GLC_uint, GLC_3DViewInstance*> PointerViewInstanceHash; typedef QHash<GLC_uint, GLC_3DViewInstance*> PointerViewInstanceHash;
//! Hash table of GLC_3DViewInstance Hash table which use a shader //! Hash table of GLC_3DViewInstance Hash table which use a shader
typedef QHash<GLuint, PointerViewInstanceHash*> HashList; typedef QHash<GLC_uint, PointerViewInstanceHash*> HashList;
//! Map Shader id to instances id (instances which use the shader) //! Map Shader id to instances id (instances which use the shader)
typedef QHash<GLC_uint, GLuint> ShaderIdToInstancesId; typedef QHash<GLC_uint, GLC_uint> ShaderIdToInstancesId;
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
//! \class GLC_3DViewCollection //! \class GLC_3DViewCollection
@ -132,7 +132,7 @@ public:
int drawableObjectsSize() const; int drawableObjectsSize() const;
//! Return the element shading group //! Return the element shading group
inline GLuint shadingGroup(GLC_uint key) const inline GLC_uint shadingGroup(GLC_uint key) const
{ return m_ShaderGroup.value(key);} { return m_ShaderGroup.value(key);}
//! Return true if the element is in a shading group //! Return true if the element is in a shading group
@ -153,6 +153,9 @@ public:
inline GLC_SpacePartitioning* spacePartitioningHandle() inline GLC_SpacePartitioning* spacePartitioningHandle()
{return m_pSpacePartitioning;} {return m_pSpacePartitioning;}
//! Return true if the collection is viewable
inline bool isViewable() const
{return m_IsViewable;}
//@} //@}
@ -164,11 +167,11 @@ public:
//! Bind the specified shader to the collection //! Bind the specified shader to the collection
/* return true if success false if shader is already bind*/ /* return true if success false if shader is already bind*/
bool bindShader(GLuint); bool bindShader(GLC_uint shaderId);
//! Unbind the specified shader from the collection //! Unbind the specified shader from the collection
/* return true if success false otherwise*/ /* return true if success false otherwise*/
bool unBindShader(GLuint); bool unBindShader(GLC_uint shaderId);
//! Unbind All shader //! Unbind All shader
bool unBindAllShader(); bool unBindAllShader();
@ -176,13 +179,13 @@ public:
//! Add a GLC_3DViewInstance in the collection //! Add a GLC_3DViewInstance in the collection
/*! return true if success false otherwise /*! return true if success false otherwise
* If shading group is specified, add instance in desire shading group*/ * If shading group is specified, add instance in desire shading group*/
bool add(const GLC_3DViewInstance& ,GLuint shaderID=0); bool add(const GLC_3DViewInstance& ,GLC_uint shaderID=0);
//! Change instance shading group //! Change instance shading group
/* Move the specified instances into /* Move the specified instances into
* the specified shading group * the specified shading group
* Return true if success false otherwise*/ * Return true if success false otherwise*/
void changeShadingGroup(GLC_uint, GLuint); void changeShadingGroup(GLC_uint instanceId, GLC_uint shaderId);
//! Remove a GLC_Geometry from the collection and delete it //! Remove a GLC_Geometry from the collection and delete it
/*! - Find the GLC_Geometry in the collection /*! - Find the GLC_Geometry in the collection
@ -192,28 +195,28 @@ public:
* - Remove the Display list container from collection * - Remove the Display list container from collection
* - Invalidate the collection * - Invalidate the collection
* return true if success false otherwise*/ * return true if success false otherwise*/
bool remove(GLC_uint Key); bool remove(GLC_uint instanceId);
//! Remove and delete all GLC_Geometry from the collection //! Remove and delete all GLC_Geometry from the collection
void clear(void); void clear(void);
//! Select a Instance //! Select a Instance
bool select(GLC_uint, bool primitive= false); bool select(GLC_uint instanceId, bool primitive= false);
//! Select all instances in current show state or in all show state //! Select all instances in current show state or in all show state
void selectAll(bool allShowState= false); void selectAll(bool allShowState= false);
//! unselect a Instance //! unselect a Instance
bool unselect(GLC_uint); bool unselect(GLC_uint instanceId);
//! unselect all Instance //! unselect all Instance
void unselectAll(); void unselectAll();
//! Set the polygon mode for all Instance //! Set the polygon mode for all Instance
void setPolygonModeForAll(GLenum, GLenum); void setPolygonModeForAll(GLenum face, GLenum mode);
//! Set Instance visibility //! Set Instance visibility
void setVisibility(const GLC_uint, const bool); void setVisibility(const GLC_uint instanceId, const bool visible);
//! Show all instances of the collection //! Show all instances of the collection
void showAll(); void showAll();
@ -223,15 +226,7 @@ public:
//! Set the Show or noShow state //! Set the Show or noShow state
inline void swapShowState() inline void swapShowState()
{ {m_IsInShowSate= !m_IsInShowSate;}
m_IsInShowSate= !m_IsInShowSate;
// Bounding box validity
if (NULL != m_pBoundingBox)
{
delete m_pBoundingBox;
m_pBoundingBox= NULL;
}
}
//! Set the LOD usage //! Set the LOD usage
inline void setLodUsage(const bool usage, GLC_Viewport* pView) inline void setLodUsage(const bool usage, GLC_Viewport* pView)
@ -261,6 +256,14 @@ public:
//! Set the attached viewport of this collection //! Set the attached viewport of this collection
inline void setAttachedViewport(GLC_Viewport* pViewport) inline void setAttachedViewport(GLC_Viewport* pViewport)
{m_pViewport= pViewport;} {m_pViewport= pViewport;}
//! Set the collection viewable state
inline void setViewable(bool viewable)
{m_IsViewable= viewable;}
//! Set VBO usage
void setVboUsage(bool usage);
//@} //@}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -287,24 +290,13 @@ public:
private: private:
//! Display collection's member //! Display collection's member
void glDraw(GLuint, glc::RenderFlag); void glDraw(GLC_uint groupID, glc::RenderFlag renderFlag);
//! Draw instances of a PointerViewInstanceHash //! Draw instances of a PointerViewInstanceHash
inline void glDrawInstancesOf(PointerViewInstanceHash*, glc::RenderFlag); inline void glDrawInstancesOf(PointerViewInstanceHash*, glc::RenderFlag);
//@} //@}
//////////////////////////////////////////////////////////////////////
/*! \name Privates services Functions*/
//@{
//////////////////////////////////////////////////////////////////////
private:
//! Set the Bounding box validity
void setBoundingBoxValidity(void);
//@}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Private members // Private members
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -312,9 +304,6 @@ private:
//! GLC_3DViewInstance Hash Table //! GLC_3DViewInstance Hash Table
ViewInstancesHash m_3DViewInstanceHash; ViewInstancesHash m_3DViewInstanceHash;
//! BoundingBox of the collection
GLC_BoundingBox* m_pBoundingBox;
//! Selected Node Hash Table //! Selected Node Hash Table
PointerViewInstanceHash m_SelectedInstances; PointerViewInstanceHash m_SelectedInstances;
@ -342,6 +331,9 @@ private:
//! The space partition usage //! The space partition usage
bool m_UseSpacePartitioning; bool m_UseSpacePartitioning;
//! Viewable state
bool m_IsViewable;
}; };

View File

@ -192,11 +192,17 @@ void GLC_3DViewInstance::setGlobalDefaultLod(int lod)
m_GlobalDefaultLOD= lod; m_GlobalDefaultLOD= lod;
} }
void GLC_3DViewInstance::setVboUsage(bool usage)
{
m_3DRep.setVboUsage(usage);
}
// Clone the instance // Clone the instance
GLC_3DViewInstance GLC_3DViewInstance::deepCopy() const GLC_3DViewInstance GLC_3DViewInstance::deepCopy() const
{ {
GLC_3DRep* pRep= dynamic_cast<GLC_3DRep*>(m_3DRep.deepCopy()); GLC_3DRep* pRep= dynamic_cast<GLC_3DRep*>(m_3DRep.deepCopy());
Q_ASSERT(NULL != pRep);
GLC_3DRep newRep(*pRep); GLC_3DRep newRep(*pRep);
delete pRep; delete pRep;
GLC_3DViewInstance cloneInstance(newRep); GLC_3DViewInstance cloneInstance(newRep);
@ -231,7 +237,7 @@ GLC_3DViewInstance GLC_3DViewInstance::instanciate()
// Set the instance Geometry // Set the instance Geometry
bool GLC_3DViewInstance::setGeometry(GLC_Geometry* pGeom) bool GLC_3DViewInstance::addGeometry(GLC_Geometry* pGeom)
{ {
if (m_3DRep.contains(pGeom)) if (m_3DRep.contains(pGeom))
{ {
@ -299,7 +305,7 @@ void GLC_3DViewInstance::render(glc::RenderFlag renderFlag, bool useLod, GLC_Vie
m_RenderProperties.setRenderingFlag(renderFlag); m_RenderProperties.setRenderingFlag(renderFlag);
// Save current OpenGL Matrix // Save current OpenGL Matrix
glPushMatrix(); GLC_Context::current()->glcPushMatrix();
OpenglVisProperties(); OpenglVisProperties();
// Change front face orientation if this instance absolute matrix is indirect // Change front face orientation if this instance absolute matrix is indirect
@ -350,7 +356,7 @@ void GLC_3DViewInstance::render(glc::RenderFlag renderFlag, bool useLod, GLC_Vie
} }
} }
// Restore OpenGL Matrix // Restore OpenGL Matrix
glPopMatrix(); GLC_Context::current()->glcPopMatrix();
// Restore front face orientation if this instance absolute matrix is indirect // Restore front face orientation if this instance absolute matrix is indirect
if (m_AbsoluteMatrix.type() == GLC_Matrix4x4::Indirect) if (m_AbsoluteMatrix.type() == GLC_Matrix4x4::Indirect)
@ -371,7 +377,7 @@ void GLC_3DViewInstance::renderForBodySelection()
m_RenderProperties.setRenderingMode(glc::BodySelection); m_RenderProperties.setRenderingMode(glc::BodySelection);
// Save current OpenGL Matrix // Save current OpenGL Matrix
glPushMatrix(); GLC_Context::current()->glcPushMatrix();
OpenglVisProperties(); OpenglVisProperties();
GLubyte colorId[4]; GLubyte colorId[4];
@ -389,7 +395,7 @@ void GLC_3DViewInstance::renderForBodySelection()
// Restore rendering mode // Restore rendering mode
m_RenderProperties.setRenderingMode(previousRenderMode); m_RenderProperties.setRenderingMode(previousRenderMode);
// Restore OpenGL Matrix // Restore OpenGL Matrix
glPopMatrix(); GLC_Context::current()->glcPopMatrix();
} }
// Display the instance in Primitive selection mode and return the body index // Display the instance in Primitive selection mode and return the body index
@ -402,7 +408,7 @@ int GLC_3DViewInstance::renderForPrimitiveSelection(GLC_uint bodyId)
m_RenderProperties.setRenderingMode(glc::PrimitiveSelection); m_RenderProperties.setRenderingMode(glc::PrimitiveSelection);
// Save current OpenGL Matrix // Save current OpenGL Matrix
glPushMatrix(); GLC_Context::current()->glcPushMatrix();
OpenglVisProperties(); OpenglVisProperties();
const int size= m_3DRep.numberOfBody(); const int size= m_3DRep.numberOfBody();
@ -423,7 +429,7 @@ int GLC_3DViewInstance::renderForPrimitiveSelection(GLC_uint bodyId)
m_RenderProperties.setRenderingMode(previousRenderMode); m_RenderProperties.setRenderingMode(previousRenderMode);
// Restore OpenGL Matrix // Restore OpenGL Matrix
glPopMatrix(); GLC_Context::current()->glcPopMatrix();
return i; return i;
} }

View File

@ -32,10 +32,11 @@
#include "../glc_state.h" #include "../glc_state.h"
#include "../geometry/glc_3drep.h" #include "../geometry/glc_3drep.h"
#include "../shading/glc_renderproperties.h" #include "../shading/glc_renderproperties.h"
#include "../glc_context.h"
#include <QMutex> #include <QMutex>
#include "glc_config.h" #include "../glc_config.h"
class GLC_Viewport; class GLC_Viewport;
@ -197,10 +198,7 @@ public:
public: public:
//! Set the instance Geometry //! Set the instance Geometry
/*! bool addGeometry(GLC_Geometry* pGeom);
* instance must be null
*/
bool setGeometry(GLC_Geometry* pGeom);
//! Remove empty geometries //! Remove empty geometries
inline void removeEmptyGeometry() inline void removeEmptyGeometry()
@ -274,6 +272,9 @@ public:
inline void setRenderProperties(const GLC_RenderProperties& renderProperties) inline void setRenderProperties(const GLC_RenderProperties& renderProperties)
{m_RenderProperties= renderProperties;} {m_RenderProperties= renderProperties;}
//! Set VBO usage
void setVboUsage(bool usage);
//@} //@}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -298,7 +299,7 @@ private:
// Polygons display mode // Polygons display mode
glPolygonMode(m_RenderProperties.polyFaceMode(), m_RenderProperties.polygonMode()); glPolygonMode(m_RenderProperties.polyFaceMode(), m_RenderProperties.polygonMode());
// Change the current matrix // Change the current matrix
glMultMatrixd(m_AbsoluteMatrix.getData()); GLC_Context::current()->glcMultMatrix(m_AbsoluteMatrix);
} }

View File

@ -180,3 +180,12 @@ GLC_StructInstance::~GLC_StructInstance()
else qDebug() << "GLC_StructInstance::~GLC_StructInstance() of empty instance"; else qDebug() << "GLC_StructInstance::~GLC_StructInstance() of empty instance";
} }
void GLC_StructInstance::updateOccurencesAbsoluteMatrix()
{
const int occurenceCount= m_ListOfOccurences.count();
for (int i= 0; i < occurenceCount; ++i)
{
m_ListOfOccurences.at(i)->updateChildrenAbsoluteMatrix();
}
}

View File

@ -166,12 +166,15 @@ public:
{m_Name= name;} {m_Name= name;}
//! Set the instance attributes //! Set the instance attributes
void setAttributes(const GLC_Attributes& attr) inline void setAttributes(const GLC_Attributes& attr)
{ {
delete m_pAttributes; delete m_pAttributes;
m_pAttributes= new GLC_Attributes(attr); m_pAttributes= new GLC_Attributes(attr);
} }
//! Update absolute matrix off children and all occurences of this instance
void updateOccurencesAbsoluteMatrix();
//@} //@}

View File

@ -41,6 +41,7 @@ GLC_StructOccurence::GLC_StructOccurence()
, m_IsVisible(true) , m_IsVisible(true)
, m_pRenderProperties(NULL) , m_pRenderProperties(NULL)
, m_AutomaticCreationOf3DViewInstance(true) , m_AutomaticCreationOf3DViewInstance(true)
, m_pRelativeMatrix(NULL)
{ {
// Update instance // Update instance
m_pStructInstance->structOccurenceCreated(this); m_pStructInstance->structOccurenceCreated(this);
@ -60,6 +61,7 @@ GLC_StructOccurence::GLC_StructOccurence(GLC_StructInstance* pStructInstance, GL
, m_IsVisible(true) , m_IsVisible(true)
, m_pRenderProperties(NULL) , m_pRenderProperties(NULL)
, m_AutomaticCreationOf3DViewInstance(true) , m_AutomaticCreationOf3DViewInstance(true)
, m_pRelativeMatrix(NULL)
{ {
// Update the number of occurences // Update the number of occurences
if (pStructInstance->hasStructOccurence()) if (pStructInstance->hasStructOccurence())
@ -107,6 +109,7 @@ GLC_StructOccurence::GLC_StructOccurence(GLC_3DRep* pRep)
, m_IsVisible(true) , m_IsVisible(true)
, m_pRenderProperties(NULL) , m_pRenderProperties(NULL)
, m_AutomaticCreationOf3DViewInstance(true) , m_AutomaticCreationOf3DViewInstance(true)
, m_pRelativeMatrix(NULL)
{ {
m_pStructInstance= new GLC_StructInstance(pRep); m_pStructInstance= new GLC_StructInstance(pRep);
setName(m_pStructInstance->name()); setName(m_pStructInstance->name());
@ -128,6 +131,7 @@ GLC_StructOccurence::GLC_StructOccurence(GLC_WorldHandle* pWorldHandle, const GL
, m_IsVisible(structOccurence.m_IsVisible) , m_IsVisible(structOccurence.m_IsVisible)
, m_pRenderProperties(NULL) , m_pRenderProperties(NULL)
, m_AutomaticCreationOf3DViewInstance(structOccurence.m_AutomaticCreationOf3DViewInstance) , m_AutomaticCreationOf3DViewInstance(structOccurence.m_AutomaticCreationOf3DViewInstance)
, m_pRelativeMatrix(NULL)
{ {
if (shareInstance) if (shareInstance)
{ {
@ -170,7 +174,7 @@ GLC_StructOccurence::GLC_StructOccurence(GLC_WorldHandle* pWorldHandle, const GL
if (NULL != m_pWorldHandle) if (NULL != m_pWorldHandle)
{ {
m_pWorldHandle->addOccurence(this, instanceIsSelected, shaderId); m_pWorldHandle->addOccurence(this, instanceIsSelected, shaderId);
if (NULL != m_pRenderProperties) if (NULL != m_pRenderProperties && this->has3DViewInstance())
{ {
m_pWorldHandle->collection()->instanceHandle(id())->setRenderProperties(*m_pRenderProperties); m_pWorldHandle->collection()->instanceHandle(id())->setRenderProperties(*m_pRenderProperties);
delete m_pRenderProperties; delete m_pRenderProperties;
@ -178,6 +182,12 @@ GLC_StructOccurence::GLC_StructOccurence(GLC_WorldHandle* pWorldHandle, const GL
} }
} }
// Check flexibility
if (NULL != structOccurence.m_pRelativeMatrix)
{
m_pRelativeMatrix= new GLC_Matrix4x4(*(structOccurence.m_pRelativeMatrix));
}
// Update Absolute matrix // Update Absolute matrix
updateAbsoluteMatrix(); updateAbsoluteMatrix();
@ -236,12 +246,23 @@ GLC_StructOccurence::~GLC_StructOccurence()
} }
delete m_pRenderProperties; delete m_pRenderProperties;
delete m_pRelativeMatrix;
} }
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Get Functions // Get Functions
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
GLC_Matrix4x4 GLC_StructOccurence::occurrenceRelativeMatrix() const
{
GLC_Matrix4x4 matrix;
if (NULL != m_pRelativeMatrix)
{
matrix= *m_pRelativeMatrix;
}
return matrix;
}
bool GLC_StructOccurence::hasRepresentation() const bool GLC_StructOccurence::hasRepresentation() const
{ {
if ((NULL != m_pStructInstance) && (m_pStructInstance->hasStructOccurence())) if ((NULL != m_pStructInstance) && (m_pStructInstance->hasStructOccurence()))
@ -288,14 +309,11 @@ QList<GLC_StructOccurence*> GLC_StructOccurence::subOccurenceList() const
for (int i= 0; i < childCount; ++i) for (int i= 0; i < childCount; ++i)
{ {
GLC_StructOccurence* pCurrentChild= m_Childs.at(i); GLC_StructOccurence* pCurrentChild= m_Childs.at(i);
subOccurence.append(pCurrentChild);
if (pCurrentChild->hasChild()) if (pCurrentChild->hasChild())
{ {
subOccurence.append(pCurrentChild->subOccurenceList()); subOccurence.append(pCurrentChild->subOccurenceList());
} }
else
{
subOccurence.append(pCurrentChild);
}
} }
return subOccurence; return subOccurence;
@ -484,13 +502,23 @@ QSet<GLC_StructReference*> GLC_StructOccurence::parentsReferences(const GLC_Stru
// Update the absolute matrix // Update the absolute matrix
GLC_StructOccurence* GLC_StructOccurence::updateAbsoluteMatrix() GLC_StructOccurence* GLC_StructOccurence::updateAbsoluteMatrix()
{ {
if (NULL != m_pParent) GLC_Matrix4x4 relativeMatrix;
if (NULL == m_pRelativeMatrix)
{ {
m_AbsoluteMatrix= m_pParent->absoluteMatrix() * m_pStructInstance->relativeMatrix(); relativeMatrix= m_pStructInstance->relativeMatrix();
} }
else else
{ {
m_AbsoluteMatrix= m_pStructInstance->relativeMatrix(); relativeMatrix= *m_pRelativeMatrix;
}
if (NULL != m_pParent)
{
m_AbsoluteMatrix= m_pParent->absoluteMatrix() * relativeMatrix;
}
else
{
m_AbsoluteMatrix= relativeMatrix;
} }
// If the occurence have a representation, update it. // If the occurence have a representation, update it.
@ -563,33 +591,6 @@ bool GLC_StructOccurence::removeChild(GLC_StructOccurence* pChild)
return m_Childs.removeOne(pChild); return m_Childs.removeOne(pChild);
} }
// Detach the occurence from the GLC_World
void GLC_StructOccurence::detach()
{
if (NULL != m_pWorldHandle)
{
// retrieve renderProperties if needed
if (m_pWorldHandle->collection()->contains(m_Uid))
{
GLC_3DViewInstance* pInstance= m_pWorldHandle->collection()->instanceHandle(m_Uid);
if (!pInstance->renderPropertiesHandle()->isDefault())
{
Q_ASSERT(NULL == m_pRenderProperties);
m_pRenderProperties= new GLC_RenderProperties(*(pInstance->renderPropertiesHandle()));
}
}
m_pWorldHandle->removeOccurence(this);
m_pWorldHandle= NULL;
if (!m_Childs.isEmpty())
{
const int size= m_Childs.size();
for (int i= 0; i < size; ++i)
{
m_Childs[i]->detach();
}
}
}
}
// Reverse Normals of this Occurence and childs // Reverse Normals of this Occurence and childs
void GLC_StructOccurence::reverseNormals() void GLC_StructOccurence::reverseNormals()
@ -611,10 +612,23 @@ bool GLC_StructOccurence::create3DViewInstance()
{ {
GLC_3DViewInstance instance(*p3DRep); GLC_3DViewInstance instance(*p3DRep);
instance.setName(name()); instance.setName(name());
// Force instance representation id // Force instance representation id
instance.setId(id()); instance.setId(id());
if (NULL != m_pRenderProperties)
{
instance.setRenderProperties(*m_pRenderProperties);
delete m_pRenderProperties;
m_pRenderProperties= NULL;
}
creationSuccess= m_pWorldHandle->collection()->add(instance); creationSuccess= m_pWorldHandle->collection()->add(instance);
m_pWorldHandle->collection()->setVisibility(m_Uid, m_IsVisible); m_pWorldHandle->collection()->setVisibility(m_Uid, m_IsVisible);
if (m_pWorldHandle->selectionSetHandle()->contains(m_Uid))
{
m_pWorldHandle->collection()->select(m_Uid);
}
} }
} }
return creationSuccess; return creationSuccess;
@ -814,3 +828,51 @@ void GLC_StructOccurence::setReference(GLC_StructReference* pRef)
m_pStructInstance->setReference(pRef); m_pStructInstance->setReference(pRef);
} }
void GLC_StructOccurence::makeFlexible(const GLC_Matrix4x4& relativeMatrix)
{
delete m_pRelativeMatrix;
m_pRelativeMatrix= new GLC_Matrix4x4(relativeMatrix);
updateChildrenAbsoluteMatrix();
}
void GLC_StructOccurence::makeRigid()
{
delete m_pRelativeMatrix;
m_pRelativeMatrix= NULL;
updateChildrenAbsoluteMatrix();
}
//////////////////////////////////////////////////////////////////////
// Private services function
//////////////////////////////////////////////////////////////////////
void GLC_StructOccurence::detach()
{
if (NULL != m_pWorldHandle)
{
// retrieve renderProperties if needed
if (m_pWorldHandle->collection()->contains(m_Uid))
{
GLC_3DViewInstance* pInstance= m_pWorldHandle->collection()->instanceHandle(m_Uid);
if (!pInstance->renderPropertiesHandle()->isDefault())
{
Q_ASSERT(NULL == m_pRenderProperties);
m_pRenderProperties= new GLC_RenderProperties(*(pInstance->renderPropertiesHandle()));
}
}
m_pWorldHandle->removeOccurence(this);
m_pWorldHandle= NULL;
if (!m_Childs.isEmpty())
{
const int size= m_Childs.size();
for (int i= 0; i < size; ++i)
{
m_Childs[i]->detach();
}
}
}
}

View File

@ -80,6 +80,9 @@ public:
inline GLC_Matrix4x4 absoluteMatrix() const inline GLC_Matrix4x4 absoluteMatrix() const
{ return m_AbsoluteMatrix;} { return m_AbsoluteMatrix;}
//! Return the surcharged relative matrix
GLC_Matrix4x4 occurrenceRelativeMatrix() const;
//! Return true if this occurence is orphan //! Return true if this occurence is orphan
inline bool isOrphan() const inline bool isOrphan() const
{ return NULL == m_pParent;} { return NULL == m_pParent;}
@ -178,7 +181,9 @@ public:
inline bool useAutomatic3DViewInstanceCreation() const inline bool useAutomatic3DViewInstanceCreation() const
{return m_AutomaticCreationOf3DViewInstance;} {return m_AutomaticCreationOf3DViewInstance;}
//! Return true if this occurence is flexible
inline bool isFlexible() const
{return (m_pRelativeMatrix != NULL);}
//@} //@}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
/*! \name Set Functions*/ /*! \name Set Functions*/
@ -250,7 +255,11 @@ public:
inline void setAutomatic3DViewInstanceCreationUsage(bool usage) inline void setAutomatic3DViewInstanceCreationUsage(bool usage)
{m_AutomaticCreationOf3DViewInstance= usage;} {m_AutomaticCreationOf3DViewInstance= usage;}
//! Make this occurence a flexible occurence
void makeFlexible(const GLC_Matrix4x4& relativeMatrix);
//! Make this occurence rigid
void makeRigid();
//@} //@}
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -297,6 +306,9 @@ private:
//! Automatique crŽation of 3DViewInstance //! Automatique crŽation of 3DViewInstance
bool m_AutomaticCreationOf3DViewInstance; bool m_AutomaticCreationOf3DViewInstance;
//! The relative matrix of this occurence if this occurence is flexible
GLC_Matrix4x4* m_pRelativeMatrix;
}; };
#endif /* GLC_STRUCTOCCURENCE_H_ */ #endif /* GLC_STRUCTOCCURENCE_H_ */

Some files were not shown because too many files have changed in this diff Show More