Merge branch 'develop' into feature/opengl

Conflicts:
	examples/Basic/CMakeLists.txt
	examples/Basic/OpenGLWidget.cpp
	examples/Basic/OpenGLWidget.h
	include/PolyVox/Impl/Timer.h
This commit is contained in:
David Williams
2015-02-08 20:49:25 +01:00
234 changed files with 52632 additions and 61900 deletions

View File

@ -1,67 +1,67 @@
# Copyright (c) 2010-2012 David Williams
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.
#
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
#
# 1. The origin of this software must not be misrepresented; you must not
# claim that you wrote the original software. If you use this software
# in a product, an acknowledgment in the product documentation would be
# appreciated but is not required.
#
# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.
#
# 3. This notice may not be removed or altered from any source
# distribution.
PROJECT(BasicExample)
#Projects source files
SET(SRC_FILES
main.cpp
OpenGLWidget.cpp
)
#Projects headers files
SET(INC_FILES
OpenGLWidget.h
)
#"Sources" and "Headers" are the group names in Visual Studio.
#They may have other uses too...
SOURCE_GROUP("Sources" FILES ${SRC_FILES})
SOURCE_GROUP("Headers" FILES ${INC_FILES})
#Tell CMake the paths for OpenGL and for PolyVox (which is just relative to our current location)
INCLUDE_DIRECTORIES(${PolyVoxCore_BINARY_DIR}/include ${PolyVoxCore_SOURCE_DIR}/include)
LINK_DIRECTORIES(${PolyVoxCore_BINARY_DIR})
#Build
ADD_EXECUTABLE(BasicExample ${SRC_FILES})
IF(MSVC)
SET_TARGET_PROPERTIES(BasicExample PROPERTIES COMPILE_FLAGS "/W4 /wd4127")
ENDIF(MSVC)
TARGET_LINK_LIBRARIES(BasicExample Qt5::OpenGL ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY} PolyVoxCore)
SET_PROPERTY(TARGET BasicExample PROPERTY FOLDER "Examples")
#Install - Only install the example in Windows
IF(WIN32)
INSTALL(TARGETS BasicExample
RUNTIME DESTINATION Examples/OpenGL/bin
LIBRARY DESTINATION Examples/OpenGL/lib
ARCHIVE DESTINATION Examples/OpenGL/lib
COMPONENT example
)
#.dlls should be installed in shared builds.
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../release/PolyVoxCore.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Release)
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../release/PolyVoxUtil.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Release)
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../debug/PolyVoxCore.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Debug)
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../debug/PolyVoxUtil.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Debug)
ENDIF(WIN32)
# Copyright (c) 2010-2012 David Williams
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.
#
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
#
# 1. The origin of this software must not be misrepresented; you must not
# claim that you wrote the original software. If you use this software
# in a product, an acknowledgment in the product documentation would be
# appreciated but is not required.
#
# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.
#
# 3. This notice may not be removed or altered from any source
# distribution.
PROJECT(BasicExample)
#Projects source files
SET(SRC_FILES
main.cpp
OpenGLWidget.cpp
)
#Projects headers files
SET(INC_FILES
OpenGLWidget.h
)
#"Sources" and "Headers" are the group names in Visual Studio.
#They may have other uses too...
SOURCE_GROUP("Sources" FILES ${SRC_FILES})
SOURCE_GROUP("Headers" FILES ${INC_FILES})
#Tell CMake the paths for OpenGL and for PolyVox (which is just relative to our current location)
INCLUDE_DIRECTORIES(${PolyVoxHeaders_SOURCE_DIR})
LINK_DIRECTORIES(${PolyVoxCore_BINARY_DIR})
#Build
ADD_EXECUTABLE(BasicExample ${SRC_FILES})
IF(MSVC)
SET_TARGET_PROPERTIES(BasicExample PROPERTIES COMPILE_FLAGS "/W4 /wd4127")
ENDIF(MSVC)
TARGET_LINK_LIBRARIES(BasicExample Qt5::OpenGL ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY} PolyVoxCore)
SET_PROPERTY(TARGET BasicExample PROPERTY FOLDER "Examples")
#Install - Only install the example in Windows
IF(WIN32)
INSTALL(TARGETS BasicExample
RUNTIME DESTINATION Examples/OpenGL/bin
LIBRARY DESTINATION Examples/OpenGL/lib
ARCHIVE DESTINATION Examples/OpenGL/lib
COMPONENT example
)
#.dlls should be installed in shared builds.
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../release/PolyVoxCore.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Release)
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../release/PolyVoxUtil.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Release)
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../debug/PolyVoxCore.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Debug)
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../debug/PolyVoxUtil.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Debug)
ENDIF(WIN32)

View File

@ -1,195 +1,195 @@
#include "OpenGLWidget.h"
#include <QMouseEvent>
#include <QMatrix4x4>
#include <QtMath>
using namespace PolyVox;
using namespace std;
OpenGLWidget::OpenGLWidget(QWidget *parent)
:QGLWidget(parent)
,m_xRotation(0)
,m_yRotation(0)
{
}
void OpenGLWidget::setSurfaceMeshToRender(const PolyVox::SurfaceMesh<PositionMaterial>& surfaceMesh)
{
//Convienient access to the vertices and indices
const auto& vecIndices = surfaceMesh.getIndices();
const auto& vecVertices = surfaceMesh.getVertices();
//Create the VAO for the mesh
//glGenVertexArrays(1, &vertexArrayObject);
//glBindVertexArray(vertexArrayObject);
//The GL_ARRAY_BUFFER will contain the list of vertex positions
glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, vecVertices.size() * sizeof(PositionMaterial), vecVertices.data(), GL_STATIC_DRAW);
//and GL_ELEMENT_ARRAY_BUFFER will contain the indices
glGenBuffers(1, &indexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, vecIndices.size() * sizeof(uint32_t), vecIndices.data(), GL_STATIC_DRAW);
//We need to tell OpenGL how to understand the format of the vertex data
glEnableVertexAttribArray(0); //We're talking about shader attribute '0'
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(PositionMaterial), 0); //take the first 3 floats from every sizeof(decltype(vecVertices)::value_type)
//glBindVertexArray(0);
noOfIndices = vecIndices.size(); //Save this for the call to glDrawElements later
}
void OpenGLWidget::initializeGL()
{
initializeOpenGLFunctions();
//Print out some information about the OpenGL implementation.
std::cout << "OpenGL Implementation Details:" << std::endl;
if(glGetString(GL_VENDOR))
std::cout << "\tGL_VENDOR: " << glGetString(GL_VENDOR) << std::endl;
if(glGetString(GL_RENDERER))
std::cout << "\tGL_RENDERER: " << glGetString(GL_RENDERER) << std::endl;
if(glGetString(GL_VERSION))
std::cout << "\tGL_VERSION: " << glGetString(GL_VERSION) << std::endl;
if(glGetString(GL_SHADING_LANGUAGE_VERSION))
std::cout << "\tGL_SHADING_LANGUAGE_VERSION: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;
//Set up the clear colour
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClearDepth(1.0f);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glDepthFunc(GL_LEQUAL);
glDepthRange(0.0, 1.0);
if(!shader.addShaderFromSourceCode(QOpenGLShader::Vertex,
"#version 140\n"
"in vec4 position; //This will be the position of the vertex in model-space\n"
"uniform mat4 cameraToClipMatrix;\n"
"uniform mat4 worldToCameraMatrix;\n"
"uniform mat4 modelToWorldMatrix;\n"
"out vec4 worldPosition; //This is being passed to the fragment shader to calculate the normals\n"
"void main()\n"
"{\n"
" worldPosition = modelToWorldMatrix * position;\n"
" vec4 cameraPosition = worldToCameraMatrix * worldPosition;\n"
" gl_Position = cameraToClipMatrix * cameraPosition;\n"
"}\n"
))
{
std::cerr << shader.log().toStdString() << std::endl;
exit(EXIT_FAILURE);
}
if(!shader.addShaderFromSourceCode(QOpenGLShader::Fragment,
"#version 130\n"
"in vec4 worldPosition; //Passed in from the vertex shader\n"
"out vec4 outputColor;\n"
"void main()\n"
"{\n"
" vec3 normal = normalize(cross(dFdy(worldPosition.xyz), dFdx(worldPosition.xyz)));\n"
" float color = clamp(abs(dot(normalize(normal.xyz), vec3(0.9,0.1,0.5))), 0, 1);\n"
" outputColor = vec4(1.0, 0.5, color, 1.0);\n"
"}\n"
))
{
std::cerr << shader.log().toStdString() << std::endl;
exit(EXIT_FAILURE);
}
shader.bindAttributeLocation("position", 0);
if(!shader.link())
{
std::cerr << shader.log().toStdString() << std::endl;
exit(EXIT_FAILURE);
}
shader.bind();
QMatrix4x4 worldToCameraMatrix;
worldToCameraMatrix.translate(0, 0, -50); //Move the camera back by 50 units
shader.setUniformValue("worldToCameraMatrix", worldToCameraMatrix);
shader.release();
}
void OpenGLWidget::resizeGL(int w, int h)
{
//Setup the viewport
glViewport(0, 0, w, h);
auto aspectRatio = w / (float)h;
float zNear = 1.0;
float zFar = 1000.0;
QMatrix4x4 cameraToClipMatrix;
cameraToClipMatrix.frustum(-aspectRatio, aspectRatio, -1, 1, zNear, zFar);
shader.bind();
shader.setUniformValue("cameraToClipMatrix", cameraToClipMatrix);
shader.release();
}
void OpenGLWidget::paintGL()
{
//Clear the screen
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
QMatrix4x4 modelToWorldMatrix;
modelToWorldMatrix.rotate(m_xRotation, 0, 1, 0); //rotate around y-axis
modelToWorldMatrix.rotate(m_yRotation, 1, 0, 0); //rotate around x-axis
modelToWorldMatrix.translate(-32, -32, -32); //centre the model on the origin
shader.bind();
shader.setUniformValue("modelToWorldMatrix", modelToWorldMatrix); //Update to the latest camera matrix
//glBindVertexArray(vertexArrayObject);
glDrawElements(GL_TRIANGLES, noOfIndices, GL_UNSIGNED_INT, 0);
//glBindVertexArray(0);
shader.release();
GLenum errCode = glGetError();
if(errCode != GL_NO_ERROR)
{
std::cerr << "OpenGL Error: " << errCode << std::endl;
}
}
void OpenGLWidget::mousePressEvent(QMouseEvent* event)
{
m_CurrentMousePos = event->pos();
m_LastFrameMousePos = m_CurrentMousePos;
update();
}
void OpenGLWidget::mouseMoveEvent(QMouseEvent* event)
{
m_CurrentMousePos = event->pos();
QPoint diff = m_CurrentMousePos - m_LastFrameMousePos;
m_xRotation += diff.x();
m_yRotation += diff.y();
m_LastFrameMousePos = m_CurrentMousePos;
update();
}
#include "OpenGLWidget.h"
#include <QMouseEvent>
#include <QMatrix4x4>
#include <QtMath>
using namespace PolyVox;
using namespace std;
OpenGLWidget::OpenGLWidget(QWidget *parent)
:QGLWidget(parent)
,m_xRotation(0)
,m_yRotation(0)
{
}
void OpenGLWidget::setSurfaceMeshToRender(const PolyVox::SurfaceMesh<PositionMaterial>& surfaceMesh)
{
//Convienient access to the vertices and indices
const auto& vecIndices = surfaceMesh.getIndices();
const auto& vecVertices = surfaceMesh.getVertices();
//Create the VAO for the mesh
//glGenVertexArrays(1, &vertexArrayObject);
//glBindVertexArray(vertexArrayObject);
//The GL_ARRAY_BUFFER will contain the list of vertex positions
glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, vecVertices.size() * sizeof(PositionMaterial), vecVertices.data(), GL_STATIC_DRAW);
//and GL_ELEMENT_ARRAY_BUFFER will contain the indices
glGenBuffers(1, &indexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, vecIndices.size() * sizeof(uint32_t), vecIndices.data(), GL_STATIC_DRAW);
//We need to tell OpenGL how to understand the format of the vertex data
glEnableVertexAttribArray(0); //We're talking about shader attribute '0'
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(PositionMaterial), 0); //take the first 3 floats from every sizeof(decltype(vecVertices)::value_type)
//glBindVertexArray(0);
noOfIndices = vecIndices.size(); //Save this for the call to glDrawElements later
}
void OpenGLWidget::initializeGL()
{
initializeOpenGLFunctions();
//Print out some information about the OpenGL implementation.
std::cout << "OpenGL Implementation Details:" << std::endl;
if(glGetString(GL_VENDOR))
std::cout << "\tGL_VENDOR: " << glGetString(GL_VENDOR) << std::endl;
if(glGetString(GL_RENDERER))
std::cout << "\tGL_RENDERER: " << glGetString(GL_RENDERER) << std::endl;
if(glGetString(GL_VERSION))
std::cout << "\tGL_VERSION: " << glGetString(GL_VERSION) << std::endl;
if(glGetString(GL_SHADING_LANGUAGE_VERSION))
std::cout << "\tGL_SHADING_LANGUAGE_VERSION: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;
//Set up the clear colour
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClearDepth(1.0f);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glDepthFunc(GL_LEQUAL);
glDepthRange(0.0, 1.0);
if(!shader.addShaderFromSourceCode(QOpenGLShader::Vertex,
"#version 140\n"
"in vec4 position; //This will be the position of the vertex in model-space\n"
"uniform mat4 cameraToClipMatrix;\n"
"uniform mat4 worldToCameraMatrix;\n"
"uniform mat4 modelToWorldMatrix;\n"
"out vec4 worldPosition; //This is being passed to the fragment shader to calculate the normals\n"
"void main()\n"
"{\n"
" worldPosition = modelToWorldMatrix * position;\n"
" vec4 cameraPosition = worldToCameraMatrix * worldPosition;\n"
" gl_Position = cameraToClipMatrix * cameraPosition;\n"
"}\n"
))
{
std::cerr << shader.log().toStdString() << std::endl;
exit(EXIT_FAILURE);
}
if(!shader.addShaderFromSourceCode(QOpenGLShader::Fragment,
"#version 130\n"
"in vec4 worldPosition; //Passed in from the vertex shader\n"
"out vec4 outputColor;\n"
"void main()\n"
"{\n"
" vec3 normal = normalize(cross(dFdy(worldPosition.xyz), dFdx(worldPosition.xyz)));\n"
" float color = clamp(abs(dot(normalize(normal.xyz), vec3(0.9,0.1,0.5))), 0, 1);\n"
" outputColor = vec4(1.0, 0.5, color, 1.0);\n"
"}\n"
))
{
std::cerr << shader.log().toStdString() << std::endl;
exit(EXIT_FAILURE);
}
shader.bindAttributeLocation("position", 0);
if(!shader.link())
{
std::cerr << shader.log().toStdString() << std::endl;
exit(EXIT_FAILURE);
}
shader.bind();
QMatrix4x4 worldToCameraMatrix;
worldToCameraMatrix.translate(0, 0, -50); //Move the camera back by 50 units
shader.setUniformValue("worldToCameraMatrix", worldToCameraMatrix);
shader.release();
}
void OpenGLWidget::resizeGL(int w, int h)
{
//Setup the viewport
glViewport(0, 0, w, h);
auto aspectRatio = w / (float)h;
float zNear = 1.0;
float zFar = 1000.0;
QMatrix4x4 cameraToClipMatrix;
cameraToClipMatrix.frustum(-aspectRatio, aspectRatio, -1, 1, zNear, zFar);
shader.bind();
shader.setUniformValue("cameraToClipMatrix", cameraToClipMatrix);
shader.release();
}
void OpenGLWidget::paintGL()
{
//Clear the screen
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
QMatrix4x4 modelToWorldMatrix;
modelToWorldMatrix.rotate(m_xRotation, 0, 1, 0); //rotate around y-axis
modelToWorldMatrix.rotate(m_yRotation, 1, 0, 0); //rotate around x-axis
modelToWorldMatrix.translate(-32, -32, -32); //centre the model on the origin
shader.bind();
shader.setUniformValue("modelToWorldMatrix", modelToWorldMatrix); //Update to the latest camera matrix
//glBindVertexArray(vertexArrayObject);
glDrawElements(GL_TRIANGLES, noOfIndices, GL_UNSIGNED_INT, 0);
//glBindVertexArray(0);
shader.release();
GLenum errCode = glGetError();
if(errCode != GL_NO_ERROR)
{
std::cerr << "OpenGL Error: " << errCode << std::endl;
}
}
void OpenGLWidget::mousePressEvent(QMouseEvent* event)
{
m_CurrentMousePos = event->pos();
m_LastFrameMousePos = m_CurrentMousePos;
update();
}
void OpenGLWidget::mouseMoveEvent(QMouseEvent* event)
{
m_CurrentMousePos = event->pos();
QPoint diff = m_CurrentMousePos - m_LastFrameMousePos;
m_xRotation += diff.x();
m_yRotation += diff.y();
m_LastFrameMousePos = m_CurrentMousePos;
update();
}

View File

@ -1,71 +1,71 @@
/*******************************************************************************
Copyright (c) 2005-2009 David Williams
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*******************************************************************************/
#ifndef __BasicExample_OpenGLWidget_H__
#define __BasicExample_OpenGLWidget_H__
#include "PolyVoxCore/SurfaceMesh.h"
#include <QOpenGLFunctions>
#include <QGLWidget>
#include <QOpenGLShaderProgram>
#include <QOpenGLVertexArrayObject>
#include <QOpenGLBuffer>
class OpenGLWidget : public QGLWidget, protected QOpenGLFunctions
{
public:
//Constructor
OpenGLWidget(QWidget *parent);
//Mouse handling
void mouseMoveEvent(QMouseEvent* event);
void mousePressEvent(QMouseEvent* event);
//Convert a SurfaceMesh to OpenGL index/vertex buffers
void setSurfaceMeshToRender(const PolyVox::SurfaceMesh<PolyVox::PositionMaterial>& surfaceMesh);
protected:
//Qt OpenGL functions
void initializeGL();
void resizeGL(int w, int h);
void paintGL();
private:
//Index/vertex buffer data
GLuint noOfIndices;
GLuint indexBuffer;
GLuint vertexBuffer;
GLuint vertexArrayObject;
QOpenGLShaderProgram shader;
//Mouse data
QPoint m_LastFrameMousePos;
QPoint m_CurrentMousePos;
int m_xRotation;
int m_yRotation;
};
#endif //__BasicExample_OpenGLWidget_H__
/*******************************************************************************
Copyright (c) 2005-2009 David Williams
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*******************************************************************************/
#ifndef __BasicExample_OpenGLWidget_H__
#define __BasicExample_OpenGLWidget_H__
#include "PolyVoxCore/SurfaceMesh.h"
#include <QOpenGLFunctions>
#include <QGLWidget>
#include <QOpenGLShaderProgram>
#include <QOpenGLVertexArrayObject>
#include <QOpenGLBuffer>
class OpenGLWidget : public QGLWidget, protected QOpenGLFunctions
{
public:
//Constructor
OpenGLWidget(QWidget *parent);
//Mouse handling
void mouseMoveEvent(QMouseEvent* event);
void mousePressEvent(QMouseEvent* event);
//Convert a SurfaceMesh to OpenGL index/vertex buffers
void setSurfaceMeshToRender(const PolyVox::SurfaceMesh<PolyVox::PositionMaterial>& surfaceMesh);
protected:
//Qt OpenGL functions
void initializeGL();
void resizeGL(int w, int h);
void paintGL();
private:
//Index/vertex buffer data
GLuint noOfIndices;
GLuint indexBuffer;
GLuint vertexBuffer;
GLuint vertexArrayObject;
QOpenGLShaderProgram shader;
//Mouse data
QPoint m_LastFrameMousePos;
QPoint m_CurrentMousePos;
int m_xRotation;
int m_yRotation;
};
#endif //__BasicExample_OpenGLWidget_H__

View File

@ -1,95 +1,95 @@
/*******************************************************************************
Copyright (c) 2005-2009 David Williams
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*******************************************************************************/
#include "OpenGLWidget.h"
#include "PolyVoxCore/CubicSurfaceExtractor.h"
#include "PolyVoxCore/MarchingCubesSurfaceExtractor.h"
#include "PolyVoxCore/SurfaceMesh.h"
#include "PolyVoxCore/SimpleVolume.h"
#include <QApplication>
//Use the PolyVox namespace
using namespace PolyVox;
void createSphereInVolume(SimpleVolume<uint8_t>& volData, float fRadius)
{
//This vector hold the position of the center of the volume
Vector3DFloat v3dVolCenter(volData.getWidth() / 2, volData.getHeight() / 2, volData.getDepth() / 2);
//This three-level for loop iterates over every voxel in the volume
for (int z = 0; z < volData.getDepth(); z++)
{
for (int y = 0; y < volData.getHeight(); y++)
{
for (int x = 0; x < volData.getWidth(); x++)
{
//Store our current position as a vector...
Vector3DFloat v3dCurrentPos(x,y,z);
//And compute how far the current position is from the center of the volume
float fDistToCenter = (v3dCurrentPos - v3dVolCenter).length();
uint8_t uVoxelValue = 0;
//If the current voxel is less than 'radius' units from the center then we make it solid.
if(fDistToCenter <= fRadius)
{
//Our new voxel value
uVoxelValue = 255;
}
//Wrte the voxel value into the volume
volData.setVoxelAt(x, y, z, uVoxelValue);
}
}
}
}
int main(int argc, char *argv[])
{
//Create and show the Qt OpenGL window
QApplication app(argc, argv);
OpenGLWidget openGLWidget(0);
openGLWidget.show();
//Create an empty volume and then place a sphere in it
SimpleVolume<uint8_t> volData(PolyVox::Region(Vector3DInt32(0,0,0), Vector3DInt32(63, 63, 63)));
createSphereInVolume(volData, 30);
//A mesh object to hold the result of surface extraction
SurfaceMesh<PositionMaterial> mesh;
//Create a surface extractor. Comment out one of the following two lines to decide which type gets created.
CubicSurfaceExtractor< SimpleVolume<uint8_t> > surfaceExtractor(&volData, volData.getEnclosingRegion(), &mesh);
//MarchingCubesSurfaceExtractor< SimpleVolume<uint8_t> > surfaceExtractor(&volData, volData.getEnclosingRegion(), &mesh);
//Execute the surface extractor.
surfaceExtractor.execute();
//Pass the surface to the OpenGL window
openGLWidget.setSurfaceMeshToRender(mesh);
//Run the message pump.
return app.exec();
/*******************************************************************************
Copyright (c) 2005-2009 David Williams
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*******************************************************************************/
#include "OpenGLWidget.h"
#include "PolyVox/CubicSurfaceExtractor.h"
#include "PolyVox/MarchingCubesSurfaceExtractor.h"
#include "PolyVox/Mesh.h"
#include "PolyVox/PagedVolume.h"
#include <QApplication>
//Use the PolyVox namespace
using namespace PolyVox;
void createSphereInVolume(PagedVolume<uint8_t>& volData, float fRadius)
{
//This vector hold the position of the center of the volume
Vector3DFloat v3dVolCenter(volData.getWidth() / 2, volData.getHeight() / 2, volData.getDepth() / 2);
//This three-level for loop iterates over every voxel in the volume
for (int z = 0; z < volData.getDepth(); z++)
{
for (int y = 0; y < volData.getHeight(); y++)
{
for (int x = 0; x < volData.getWidth(); x++)
{
//Store our current position as a vector...
Vector3DFloat v3dCurrentPos(x,y,z);
//And compute how far the current position is from the center of the volume
float fDistToCenter = (v3dCurrentPos - v3dVolCenter).length();
uint8_t uVoxelValue = 0;
//If the current voxel is less than 'radius' units from the center then we make it solid.
if(fDistToCenter <= fRadius)
{
//Our new voxel value
uVoxelValue = 255;
}
//Wrte the voxel value into the volume
volData.setVoxelAt(x, y, z, uVoxelValue);
}
}
}
}
int main(int argc, char *argv[])
{
//Create and show the Qt OpenGL window
QApplication app(argc, argv);
OpenGLWidget openGLWidget(0);
openGLWidget.show();
//Create an empty volume and then place a sphere in it
PagedVolume<uint8_t> volData(PolyVox::Region(Vector3DInt32(0, 0, 0), Vector3DInt32(63, 63, 63)));
createSphereInVolume(volData, 30);
// Extract the surface for the specified region of the volume. Uncomment the line for the kind of surface extraction you want to see.
auto mesh = extractCubicMesh(&volData, volData.getEnclosingRegion());
//auto mesh = extractMarchingCubesMesh(&volData, volData.getEnclosingRegion());
// The surface extractor outputs the mesh in an efficient compressed format which is not directly suitable for rendering. The easiest approach is to
// decode this on the CPU as shown below, though more advanced applications can upload the compressed mesh to the GPU and decompress in shader code.
auto decodedMesh = decodeMesh(mesh);
//Pass the surface to the OpenGL window
openGLWidget.addMesh(decodedMesh);
//openGLWidget.addMesh(mesh2);
openGLWidget.setViewableRegion(volData.getEnclosingRegion());
//Run the message pump.
return app.exec();
}

7
examples/CMakeLists.txt Normal file
View File

@ -0,0 +1,7 @@
ADD_SUBDIRECTORY(common)
ADD_SUBDIRECTORY(Basic)
ADD_SUBDIRECTORY(Paging)
ADD_SUBDIRECTORY(OpenGL)
ADD_SUBDIRECTORY(SmoothLOD)
ADD_SUBDIRECTORY(DecodeOnGPU)
ADD_SUBDIRECTORY(Python)

View File

@ -0,0 +1,67 @@
# Copyright (c) 2010-2012 David Williams
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.
#
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
#
# 1. The origin of this software must not be misrepresented; you must not
# claim that you wrote the original software. If you use this software
# in a product, an acknowledgment in the product documentation would be
# appreciated but is not required.
#
# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.
#
# 3. This notice may not be removed or altered from any source
# distribution.
CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
PROJECT(DecodeOnGPUExample)
#Projects source files
SET(SRC_FILES
main.cpp
../common/OpenGLWidget.cpp
)
#Projects headers files
SET(INC_FILES
OpenGLWidget.h
)
add_definitions(-DGLEW_STATIC)
FIND_PACKAGE(OpenGL REQUIRED)
#Tell CMake the paths for OpenGL and for PolyVox (which is just relative to our current location)
INCLUDE_DIRECTORIES(${OPENGL_INCLUDE_DIR} ${PolyVoxHeaders_SOURCE_DIR} ${GLEW_SOURCE_DIR})
#This will include the shader files inside the compiled binary
QT4_ADD_RESOURCES(COMMON_RESOURCES_RCC ../common/example.qrc)
QT4_ADD_RESOURCES(DECODE_RESOURCES_RCC decode.qrc)
# Put the resources in a seperate folder in Visual Studio
SOURCE_GROUP("Resource Files" FILES ../common/example.qrc ${COMMON_RESOURCES_RCC} decode.qrc ${DECODE_RESOURCES_RCC})
#Build
ADD_EXECUTABLE(DecodeOnGPUExample ${SRC_FILES} ${COMMON_RESOURCES_RCC} ${DECODE_RESOURCES_RCC})
IF(MSVC)
SET_TARGET_PROPERTIES(DecodeOnGPUExample PROPERTIES COMPILE_FLAGS "/W4 /wd4127")
ENDIF(MSVC)
TARGET_LINK_LIBRARIES(DecodeOnGPUExample glew ${QT_LIBRARIES} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY})
SET_PROPERTY(TARGET DecodeOnGPUExample PROPERTY FOLDER "Examples")
#Install - Only install the example in Windows
IF(WIN32)
INSTALL(TARGETS DecodeOnGPUExample
RUNTIME DESTINATION Examples/OpenGL/bin
LIBRARY DESTINATION Examples/OpenGL/lib
ARCHIVE DESTINATION Examples/OpenGL/lib
COMPONENT example
)
ENDIF(WIN32)

View File

@ -0,0 +1,19 @@
#version 130
// Passed in from the vertex shader
in vec4 worldPosition;
in vec4 worldNormal;
// the color that gets written to the display
out vec4 outputColor;
void main()
{
// Again, for the purposes of these examples we cannot be sure that per-vertex normals are provided. A sensible fallback
// is to use this little trick to compute per-fragment flat-shaded normals from the world positions using derivative operations.
//vec3 normal = normalize(cross(dFdy(worldPosition.xyz), dFdx(worldPosition.xyz)));
// We are just using the normal as the output color, and making it lighter so it looks a bit nicer.
// Obviously a real shader would also do texuring, lighting, or whatever is required for the application.
outputColor = vec4(abs(worldNormal.xyz) * 0.5 + vec3(0.5, 0.5, 0.5), 1.0);
}

View File

@ -0,0 +1,6 @@
<!DOCTYPE RCC><RCC version="1.0">
<qresource>
<file>decode.vert</file>
<file>decode.frag</file>
</qresource>
</RCC>

View File

@ -0,0 +1,46 @@
#version 140
in uvec4 position; // This will be the position of the vertex in model-space
in uint normal;
// The usual matrices are provided
uniform mat4 cameraToClipMatrix;
uniform mat4 worldToCameraMatrix;
uniform mat4 modelToWorldMatrix;
// This will be used by the fragment shader to calculate flat-shaded normals. This is an unconventional approach
// but we use it in this example framework because not all surface extractor generate surface normals.
out vec4 worldPosition;
out vec4 worldNormal;
// Returns +/- 1
vec2 signNotZero(vec2 v)
{
return vec2((v.x >= 0.0) ? +1.0 : -1.0, (v.y >= 0.0) ? +1.0 : -1.0);
}
void main()
{
vec4 decodedPosition = position;
decodedPosition.xyz = decodedPosition.xyz * (1.0 / 256.0);
//Get the encoded bytes of the normal
uint encodedX = (normal >> 8u) & 0xFFu;
uint encodedY = (normal) & 0xFFu;
// Map to range [-1.0, +1.0]
vec2 e = vec2(encodedX, encodedY);
e = e * vec2(1.0 / 127.5, 1.0 / 127.5);
e = e - vec2(1.0, 1.0);
// Now decode normal using listing 2 of http://jcgt.org/published/0003/02/01/
vec3 v = vec3(e.xy, 1.0 - abs(e.x) - abs(e.y));
if (v.z < 0) v.xy = (1.0 - abs(v.yx)) * signNotZero(v.xy);
worldNormal.xyz = normalize(v);
worldNormal.w = 1.0;
// Standard sequence of OpenGL transformations.
worldPosition = modelToWorldMatrix * decodedPosition;
vec4 cameraPosition = worldToCameraMatrix * worldPosition;
gl_Position = cameraToClipMatrix * cameraPosition;
}

View File

@ -0,0 +1,167 @@
/*******************************************************************************
Copyright (c) 2005-2009 David Williams
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*******************************************************************************/
#include "OpenGLWidget.h"
#include "PolyVox/CubicSurfaceExtractor.h"
#include "PolyVox/MarchingCubesSurfaceExtractor.h"
#include "PolyVox/Mesh.h"
#include "PolyVox/PagedVolume.h"
#include <QApplication>
//Use the PolyVox namespace
using namespace PolyVox;
void createSphereInVolume(PagedVolume<uint8_t>& volData, float fRadius)
{
//This vector hold the position of the center of the volume
Vector3DFloat v3dVolCenter(volData.getWidth() / 2, volData.getHeight() / 2, volData.getDepth() / 2);
//This three-level for loop iterates over every voxel in the volume
for (int z = 0; z < volData.getDepth(); z++)
{
for (int y = 0; y < volData.getHeight(); y++)
{
for (int x = 0; x < volData.getWidth(); x++)
{
//Store our current position as a vector...
Vector3DFloat v3dCurrentPos(x,y,z);
//And compute how far the current position is from the center of the volume
float fDistToCenter = (v3dCurrentPos - v3dVolCenter).length();
uint8_t uVoxelValue = 0;
//If the current voxel is less than 'radius' units from the center then we make it solid.
if(fDistToCenter <= fRadius)
{
//Our new voxel value
uVoxelValue = 255;
}
//Wrte the voxel value into the volume
volData.setVoxelAt(x, y, z, uVoxelValue);
}
}
}
}
OpenGLMeshData buildOpenGLMeshData(const PolyVox::Mesh< PolyVox::MarchingCubesVertex< uint8_t > >& surfaceMesh, const PolyVox::Vector3DInt32& translation = PolyVox::Vector3DInt32(0, 0, 0), float scale = 1.0f)
{
// Convienient access to the vertices and indices
const auto& vecIndices = surfaceMesh.getIndices();
const auto& vecVertices = surfaceMesh.getVertices();
// This struct holds the OpenGL properties (buffer handles, etc) which will be used
// to render our mesh. We copy the data from the PolyVox mesh into this structure.
OpenGLMeshData meshData;
// Create the VAO for the mesh
glGenVertexArrays(1, &(meshData.vertexArrayObject));
glBindVertexArray(meshData.vertexArrayObject);
// The GL_ARRAY_BUFFER will contain the list of vertex positions
glGenBuffers(1, &(meshData.vertexBuffer));
glBindBuffer(GL_ARRAY_BUFFER, meshData.vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, vecVertices.size() * sizeof(MarchingCubesVertex< uint8_t >), vecVertices.data(), GL_STATIC_DRAW);
// and GL_ELEMENT_ARRAY_BUFFER will contain the indices
glGenBuffers(1, &(meshData.indexBuffer));
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, meshData.indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, vecIndices.size() * sizeof(uint32_t), vecIndices.data(), GL_STATIC_DRAW);
// Every surface extractor outputs valid positions for the vertices, so tell OpenGL how these are laid out
glEnableVertexAttribArray(0); // Attrib '0' is the vertex positions
glVertexAttribIPointer(0, 3, GL_UNSIGNED_SHORT, sizeof(MarchingCubesVertex< uint8_t >), (GLvoid*)(offsetof(MarchingCubesVertex< uint8_t >, encodedPosition))); //take the first 3 floats from every sizeof(decltype(vecVertices)::value_type)
// Some surface extractors also generate normals, so tell OpenGL how these are laid out. If a surface extractor
// does not generate normals then nonsense values are written into the buffer here and sghould be ignored by the
// shader. This is mostly just to simplify this example code - in a real application you will know whether your
// chosen surface extractor generates normals and can skip uploading them if not.
glEnableVertexAttribArray(1); // Attrib '1' is the vertex normals.
glVertexAttribIPointer(1, 1, GL_UNSIGNED_SHORT, sizeof(MarchingCubesVertex< uint8_t >), (GLvoid*)(offsetof(MarchingCubesVertex< uint8_t >, encodedNormal)));
// Finally a surface extractor will probably output additional data. This is highly application dependant. For this example code
// we're just uploading it as a set of bytes which we can read individually, but real code will want to do something specialised here.
glEnableVertexAttribArray(2); //We're talking about shader attribute '2'
GLint size = (std::min)(sizeof(uint8_t), size_t(4)); // Can't upload more that 4 components (vec4 is GLSL's biggest type)
glVertexAttribIPointer(2, size, GL_UNSIGNED_BYTE, sizeof(MarchingCubesVertex< uint8_t >), (GLvoid*)(offsetof(MarchingCubesVertex< uint8_t >, data)));
// We're done uploading and can now unbind.
glBindVertexArray(0);
// A few additional properties can be copied across for use during rendering.
meshData.noOfIndices = vecIndices.size();
meshData.translation = QVector3D(translation.getX(), translation.getY(), translation.getZ());
meshData.scale = scale;
// Set 16 or 32-bit index buffer size.
meshData.indexType = sizeof(PolyVox::Mesh< PolyVox::MarchingCubesVertex< uint8_t > >::IndexType) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
return meshData;
}
int main(int argc, char *argv[])
{
//Create and show the Qt OpenGL window
QApplication app(argc, argv);
OpenGLWidget openGLWidget(0);
openGLWidget.show();
QSharedPointer<QGLShaderProgram> shader(new QGLShaderProgram);
if (!shader->addShaderFromSourceFile(QGLShader::Vertex, ":/decode.vert"))
{
std::cerr << shader->log().toStdString() << std::endl;
exit(EXIT_FAILURE);
}
if (!shader->addShaderFromSourceFile(QGLShader::Fragment, ":/decode.frag"))
{
std::cerr << shader->log().toStdString() << std::endl;
exit(EXIT_FAILURE);
}
openGLWidget.setShader(shader);
//Create an empty volume and then place a sphere in it
PagedVolume<uint8_t> volData(PolyVox::Region(Vector3DInt32(0, 0, 0), Vector3DInt32(63, 63, 63)));
createSphereInVolume(volData, 30);
// Extract the surface for the specified region of the volume. Uncomment the line for the kind of surface extraction you want to see.
//auto mesh = extractCubicMesh(&volData, volData.getEnclosingRegion());
auto mesh = extractMarchingCubesMesh(&volData, volData.getEnclosingRegion());
// The surface extractor outputs the mesh in an efficient compressed format which is not directly suitable for rendering. The easiest approach is to
// decode this on the CPU as shown below, though more advanced applications can upload the compressed mesh to the GPU and decompress in shader code.
//auto decodedMesh = decodeMesh(mesh);
//Pass the surface to the OpenGL window
OpenGLMeshData meshData = buildOpenGLMeshData(mesh);
openGLWidget.addMeshData(meshData);
openGLWidget.setViewableRegion(volData.getEnclosingRegion());
//Run the message pump.
return app.exec();
}

View File

@ -1,81 +1,69 @@
# Copyright (c) 2010-2012 David Williams
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.
#
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
#
# 1. The origin of this software must not be misrepresented; you must not
# claim that you wrote the original software. If you use this software
# in a product, an acknowledgment in the product documentation would be
# appreciated but is not required.
#
# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.
#
# 3. This notice may not be removed or altered from any source
# distribution.
CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
PROJECT(OpenGLExample)
#Projects source files
SET(SRC_FILES
main.cpp
OpenGLImmediateModeSupport.cpp
OpenGLSupport.cpp
OpenGLVertexBufferObjectSupport.cpp
OpenGLWidget.cpp
Shapes.cpp
)
#Projects headers files
SET(INC_FILES
OpenGLImmediateModeSupport.h
OpenGLSupport.h
OpenGLVertexBufferObjectSupport.h
OpenGLWidget.h
Shapes.h
)
add_definitions(-DGLEW_STATIC)
#"Sources" and "Headers" are the group names in Visual Studio.
#They may have other uses too...
SOURCE_GROUP("Sources" FILES ${SRC_FILES})
SOURCE_GROUP("Headers" FILES ${INC_FILES})
FIND_PACKAGE(OpenGL REQUIRED)
#Tell CMake the paths for OpenGL and for PolyVox (which is just relative to our current location)
INCLUDE_DIRECTORIES(${OPENGL_INCLUDE_DIR} ${PolyVoxCore_BINARY_DIR}/include ${PolyVoxCore_SOURCE_DIR}/include ${GLEW_SOURCE_DIR})
LINK_DIRECTORIES(${PolyVoxCore_BINARY_DIR})
#Build
ADD_EXECUTABLE(OpenGLExample ${SRC_FILES})
IF(MSVC)
SET_TARGET_PROPERTIES(OpenGLExample PROPERTIES COMPILE_FLAGS "/W4 /wd4127")
ENDIF(MSVC)
TARGET_LINK_LIBRARIES(OpenGLExample glew Qt5::OpenGL ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY} PolyVoxCore)
SET_PROPERTY(TARGET OpenGLExample PROPERTY FOLDER "Examples")
#Install - Only install the example in Windows
IF(WIN32)
INSTALL(TARGETS OpenGLExample
RUNTIME DESTINATION Examples/OpenGL/bin
LIBRARY DESTINATION Examples/OpenGL/lib
ARCHIVE DESTINATION Examples/OpenGL/lib
COMPONENT example
)
#.dlls should be installed in shared builds.
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../release/PolyVoxCore.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Release)
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../release/PolyVoxUtil.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Release)
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../debug/PolyVoxCore.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Debug)
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../debug/PolyVoxUtil.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Debug)
ENDIF(WIN32)
# Copyright (c) 2010-2012 David Williams
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.
#
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
#
# 1. The origin of this software must not be misrepresented; you must not
# claim that you wrote the original software. If you use this software
# in a product, an acknowledgment in the product documentation would be
# appreciated but is not required.
#
# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.
#
# 3. This notice may not be removed or altered from any source
# distribution.
CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
PROJECT(OpenGLExample)
#Projects source files
SET(SRC_FILES
main.cpp
../common/OpenGLWidget.cpp
Shapes.cpp
)
#Projects headers files
SET(INC_FILES
OpenGLWidget.h
Shapes.h
)
add_definitions(-DGLEW_STATIC)
FIND_PACKAGE(OpenGL REQUIRED)
#Tell CMake the paths for OpenGL and for PolyVox (which is just relative to our current location)
INCLUDE_DIRECTORIES(${OPENGL_INCLUDE_DIR} ${PolyVoxHeaders_SOURCE_DIR} ${GLEW_SOURCE_DIR})
#This will include the shader files inside the compiled binary
QT4_ADD_RESOURCES(COMMON_RESOURCES_RCC ../common/example.qrc)
QT4_ADD_RESOURCES(OPENGLEXAMPLE_RESOURCES_RCC openglexample.qrc)
# Put the resources in a seperate folder in Visual Studio
SOURCE_GROUP("Resource Files" FILES ../common/example.qrc ${COMMON_RESOURCES_RCC} openglexample.qrc ${OPENGLEXAMPLE_RESOURCES_RCC})
#Build
ADD_EXECUTABLE(OpenGLExample ${SRC_FILES} ${COMMON_RESOURCES_RCC} ${OPENGLEXAMPLE_RESOURCES_RCC})
IF(MSVC)
SET_TARGET_PROPERTIES(OpenGLExample PROPERTIES COMPILE_FLAGS "/W4 /wd4127")
ENDIF(MSVC)
TARGET_LINK_LIBRARIES(OpenGLExample glew ${QT_LIBRARIES} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY})
SET_PROPERTY(TARGET OpenGLExample PROPERTY FOLDER "Examples")
#Install - Only install the example in Windows
IF(WIN32)
INSTALL(TARGETS OpenGLExample
RUNTIME DESTINATION Examples/OpenGL/bin
LIBRARY DESTINATION Examples/OpenGL/lib
ARCHIVE DESTINATION Examples/OpenGL/lib
COMPONENT example
)
ENDIF(WIN32)

View File

@ -1,63 +0,0 @@
/*******************************************************************************
Copyright (c) 2005-2009 David Williams
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*******************************************************************************/
#include "OpenGLImmediateModeSupport.h"
#include "OpenGLSupport.h"
#include "PolyVoxCore/SurfaceMesh.h"
using namespace PolyVox;
using namespace std;
void renderRegionImmediateMode(PolyVox::SurfaceMesh<PositionMaterialNormal>& mesh, unsigned int uLodLevel)
{
const vector<PositionMaterialNormal>& vecVertices = mesh.getVertices();
const vector<uint32_t>& vecIndices = mesh.getIndices();
int beginIndex = mesh.m_vecLodRecords[uLodLevel].beginIndex;
int endIndex = mesh.m_vecLodRecords[uLodLevel].endIndex;
glBegin(GL_TRIANGLES);
//for(vector<PolyVox::uint32_t>::const_iterator iterIndex = vecIndices.begin(); iterIndex != vecIndices.end(); ++iterIndex)
for(int index = beginIndex; index < endIndex; ++index)
{
const PositionMaterialNormal& vertex = vecVertices[vecIndices[index]];
const Vector3DFloat& v3dVertexPos = vertex.getPosition();
//const Vector3DFloat v3dRegionOffset(uRegionX * g_uRegionSideLength, uRegionY * g_uRegionSideLength, uRegionZ * g_uRegionSideLength);
const Vector3DFloat v3dFinalVertexPos = v3dVertexPos + static_cast<Vector3DFloat>(mesh.m_Region.getLowerCorner());
uint8_t material = static_cast<uint8_t>(vertex.getMaterial() + 0.5);
OpenGLColour colour = convertMaterialIDToColour(material);
glColor3f(colour.red, colour.green, colour.blue);
glNormal3f(vertex.getNormal().getX(), vertex.getNormal().getY(), vertex.getNormal().getZ());
glVertex3f(v3dFinalVertexPos.getX(), v3dFinalVertexPos.getY(), v3dFinalVertexPos.getZ());
}
glEnd();
}

View File

@ -1,33 +0,0 @@
/*******************************************************************************
Copyright (c) 2005-2009 David Williams
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*******************************************************************************/
#ifndef __OpenGLExample_OpenGLImmediateModeSupport_H__
#define __OpenGLExample_OpenGLImmediateModeSupport_H__
#include "PolyVoxCore/PolyVoxForwardDeclarations.h"
#include "glew/glew.h"
void renderRegionImmediateMode(PolyVox::SurfaceMesh<PolyVox::PositionMaterialNormal>& mesh, unsigned int uLodLevel);
#endif //__OpenGLExample_OpenGLImmediateModeSupport_H__

View File

@ -1,66 +0,0 @@
/*******************************************************************************
Copyright (c) 2005-2009 David Williams
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*******************************************************************************/
#include "OpenGLSupport.h"
using namespace PolyVox;
OpenGLColour convertMaterialIDToColour(uint8_t materialID)
{
OpenGLColour colour;
switch(materialID)
{
case 1:
colour.red = 1.0f;
colour.green = 0.0f;
colour.blue = 0.0f;
break;
case 2:
colour.red = 0.0f;
colour.green = 1.0f;
colour.blue = 0.0f;
break;
case 3:
colour.red = 0.0f;
colour.green = 0.0f;
colour.blue = 1.0f;
break;
case 4:
colour.red = 1.0f;
colour.green = 1.0f;
colour.blue = 0.0f;
break;
case 5:
colour.red = 1.0f;
colour.green = 0.0f;
colour.blue = 1.0f;
break;
default:
colour.red = 1.0f;
colour.green = 1.0f;
colour.blue = 1.0f;
}
return colour;
}

View File

@ -1,40 +0,0 @@
/*******************************************************************************
Copyright (c) 2005-2009 David Williams
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*******************************************************************************/
#ifndef __OpenGLExample_OpenGLSupport_H__
#define __OpenGLExample_OpenGLSupport_H__
#include "PolyVoxCore/PolyVoxForwardDeclarations.h"
#include "glew/glew.h"
struct OpenGLColour
{
GLfloat red;
GLfloat green;
GLfloat blue;
};
OpenGLColour convertMaterialIDToColour(uint8_t materialID);
#endif //__OpenGLExample_OpenGLSupport_H__

View File

@ -1,124 +0,0 @@
/*******************************************************************************
Copyright (c) 2005-2009 David Williams
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*******************************************************************************/
#include "OpenGLSupport.h"
#include "OpenGLVertexBufferObjectSupport.h"
#include "PolyVoxCore/SurfaceMesh.h"
using namespace PolyVox;
using namespace std;
OpenGLSurfaceMesh BuildOpenGLSurfaceMesh(const SurfaceMesh<PositionMaterialNormal>& mesh)
{
//Represents our filled in OpenGL vertex and index buffer objects.
OpenGLSurfaceMesh result;
//The source
result.sourceMesh = &mesh;
//Convienient access to the vertices and indices
const vector<PositionMaterialNormal>& vecVertices = mesh.getVertices();
const vector<uint32_t>& vecIndices = mesh.getIndices();
//If we have any indices...
if(!vecIndices.empty())
{
//Create an OpenGL index buffer
glGenBuffers(1, &result.indexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, result.indexBuffer);
//Get a pointer to the first index
GLvoid* pIndices = (GLvoid*)(&(vecIndices[0]));
//Fill the OpenGL index buffer with our data.
glBufferData(GL_ELEMENT_ARRAY_BUFFER, vecIndices.size() * sizeof(uint32_t), pIndices, GL_STATIC_DRAW);
}
result.noOfIndices = vecIndices.size();
glGenBuffers(1, &result.vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, result.vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, vecVertices.size() * sizeof(GLfloat) * 9, 0, GL_STATIC_DRAW);
GLfloat* ptr = (GLfloat*)glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE);
for(vector<PositionMaterialNormal>::const_iterator iterVertex = vecVertices.begin(); iterVertex != vecVertices.end(); ++iterVertex)
{
const PositionMaterialNormal& vertex = *iterVertex;
const Vector3DFloat& v3dVertexPos = vertex.getPosition();
//const Vector3DFloat v3dRegionOffset(uRegionX * g_uRegionSideLength, uRegionY * g_uRegionSideLength, uRegionZ * g_uRegionSideLength);
const Vector3DFloat v3dFinalVertexPos = v3dVertexPos + static_cast<Vector3DFloat>(mesh.m_Region.getLowerCorner());
*ptr = v3dFinalVertexPos.getX();
ptr++;
*ptr = v3dFinalVertexPos.getY();
ptr++;
*ptr = v3dFinalVertexPos.getZ();
ptr++;
*ptr = vertex.getNormal().getX();
ptr++;
*ptr = vertex.getNormal().getY();
ptr++;
*ptr = vertex.getNormal().getZ();
ptr++;
uint8_t material = static_cast<uint8_t>(vertex.getMaterial() + 0.5);
OpenGLColour colour = convertMaterialIDToColour(material);
*ptr = colour.red;
ptr++;
*ptr = colour.green;
ptr++;
*ptr = colour.blue;
ptr++;
}
glUnmapBuffer(GL_ARRAY_BUFFER);
return result;
}
void renderRegionVertexBufferObject(const OpenGLSurfaceMesh& openGLSurfaceMesh, unsigned int uLodLevel)
{
int beginIndex = openGLSurfaceMesh.sourceMesh->m_vecLodRecords[uLodLevel].beginIndex;
int endIndex = openGLSurfaceMesh.sourceMesh->m_vecLodRecords[uLodLevel].endIndex;
glBindBuffer(GL_ARRAY_BUFFER, openGLSurfaceMesh.vertexBuffer);
glVertexPointer(3, GL_FLOAT, 36, 0);
glNormalPointer(GL_FLOAT, 36, (GLvoid*)12);
glColorPointer(3, GL_FLOAT, 36, (GLvoid*)24);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, openGLSurfaceMesh.indexBuffer);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
//glDrawElements(GL_TRIANGLES, openGLSurfaceMesh.noOfIndices, GL_UNSIGNED_INT, 0);
glDrawRangeElements(GL_TRIANGLES, beginIndex, endIndex-1, endIndex - beginIndex,/* openGLSurfaceMesh.noOfIndices,*/ GL_UNSIGNED_INT, 0);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
}

View File

@ -1,42 +0,0 @@
/*******************************************************************************
Copyright (c) 2005-2009 David Williams
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*******************************************************************************/
#ifndef __OpenGLExample_OpenGLVertexBufferObjectSupport_H__
#define __OpenGLExample_OpenGLVertexBufferObjectSupport_H__
#include "PolyVoxCore/PolyVoxForwardDeclarations.h"
#include "glew/glew.h"
struct OpenGLSurfaceMesh
{
GLulong noOfIndices;
GLuint indexBuffer;
GLuint vertexBuffer;
const PolyVox::SurfaceMesh<PolyVox::PositionMaterialNormal>* sourceMesh;
};
OpenGLSurfaceMesh BuildOpenGLSurfaceMesh(const PolyVox::SurfaceMesh<PolyVox::PositionMaterialNormal>& mesh);
void renderRegionVertexBufferObject(const OpenGLSurfaceMesh& openGLSurfaceMesh, unsigned int uLodLevel);
#endif //__OpenGLExample_OpenGLVertexBufferObjectSupport_H__

View File

@ -1,246 +0,0 @@
/*******************************************************************************
Copyright (c) 2005-2009 David Williams
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*******************************************************************************/
#include "OpenGLWidget.h"
#include <QMouseEvent>
#include "PolyVoxCore/GradientEstimators.h"
#include "PolyVoxCore/MaterialDensityPair.h"
#include "PolyVoxCore/MarchingCubesSurfaceExtractor.h"
//Some namespaces we need
using namespace std;
using namespace PolyVox;
using namespace std;
OpenGLWidget::OpenGLWidget(QWidget *parent)
:QGLWidget(parent)
,m_volData(0)
{
m_xRotation = 0;
m_yRotation = 0;
m_uRegionSideLength = 32;
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
timer->start(0);
}
void OpenGLWidget::setVolume(PolyVox::LargeVolume<MaterialDensityPair44>* volData)
{
//First we free anything from the previous volume (if there was one).
m_mapOpenGLSurfaceMeshes.clear();
m_mapSurfaceMeshes.clear();
m_volData = volData;
//If we have any volume data then generate the new surface patches.
if(m_volData != 0)
{
m_uVolumeWidthInRegions = volData->getWidth() / m_uRegionSideLength;
m_uVolumeHeightInRegions = volData->getHeight() / m_uRegionSideLength;
m_uVolumeDepthInRegions = volData->getDepth() / m_uRegionSideLength;
//Our volume is broken down into cuboid regions, and we create one mesh for each region.
//This three-level for loop iterates over each region.
for(uint16_t uRegionZ = 0; uRegionZ < m_uVolumeDepthInRegions; ++uRegionZ)
{
std::cout << "uRegionZ = " << uRegionZ << " of " << m_uVolumeDepthInRegions << std::endl;
for(uint16_t uRegionY = 0; uRegionY < m_uVolumeHeightInRegions; ++uRegionY)
{
for(uint16_t uRegionX = 0; uRegionX < m_uVolumeWidthInRegions; ++uRegionX)
{
//Compute the extents of the current region
//FIXME - This is a little complex? PolyVox could
//provide more functions for dealing with regions?
int32_t regionStartX = uRegionX * m_uRegionSideLength;
int32_t regionStartY = uRegionY * m_uRegionSideLength;
int32_t regionStartZ = uRegionZ * m_uRegionSideLength;
int32_t regionEndX = regionStartX + m_uRegionSideLength;
int32_t regionEndY = regionStartY + m_uRegionSideLength;
int32_t regionEndZ = regionStartZ + m_uRegionSideLength;
Vector3DInt32 regLowerCorner(regionStartX, regionStartY, regionStartZ);
Vector3DInt32 regUpperCorner(regionEndX, regionEndY, regionEndZ);
//Extract the surface for this region
//extractSurface(m_volData, 0, PolyVox::Region(regLowerCorner, regUpperCorner), meshCurrent);
std::shared_ptr< SurfaceMesh<PositionMaterialNormal> > mesh(new SurfaceMesh<PositionMaterialNormal>);
MarchingCubesSurfaceExtractor< LargeVolume<MaterialDensityPair44> > surfaceExtractor(volData, PolyVox::Region(regLowerCorner, regUpperCorner), mesh.get());
surfaceExtractor.execute();
//decimatedMesh->generateAveragedFaceNormals(true);
//computeNormalsForVertices(m_volData, *(decimatedMesh.get()), SOBEL_SMOOTHED);
//*meshCurrent = getSmoothedSurface(*meshCurrent);
//mesh->smooth(0.3f);
//meshCurrent->generateAveragedFaceNormals(true);
if(mesh->m_vecTriangleIndices.size() > 0)
{
Vector3DUint8 v3dRegPos(uRegionX,uRegionY,uRegionZ);
if(m_bUseOpenGLVertexBufferObjects)
{
OpenGLSurfaceMesh openGLSurfaceMesh = BuildOpenGLSurfaceMesh(*(mesh.get()));
m_mapOpenGLSurfaceMeshes.insert(make_pair(v3dRegPos, openGLSurfaceMesh));
}
//else
//{
m_mapSurfaceMeshes.insert(make_pair(v3dRegPos, mesh));
//}
//delete meshCurrent;
}
}
}
}
//Projection matrix is dependant on volume size, so we need to set it up again.
setupProjectionMatrix();
}
}
void OpenGLWidget::initializeGL()
{
m_bUseOpenGLVertexBufferObjects = true;
if(m_bUseOpenGLVertexBufferObjects)
{
//We need GLEW to access recent OpenGL functionality
GLenum err = glewInit();
if (GLEW_OK != err)
{
/* Problem: glewInit failed, something is seriously wrong. */
cout << "GLEW Error: " << glewGetErrorString(err) << endl;
}
}
glShadeModel(GL_SMOOTH); // Enable Smooth Shading
glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background
glClearDepth(1.0f); // Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do
glEnable ( GL_COLOR_MATERIAL );
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glEnable(GL_LIGHTING);
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
glEnable(GL_LIGHT0);
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glShadeModel(GL_SMOOTH);
}
void OpenGLWidget::resizeGL(int w, int h)
{
//Setup the viewport based on the window size
glViewport(0, 0, w, h);
//Projection matrix is also dependant on the size of the current volume.
if(m_volData)
{
setupProjectionMatrix();
}
}
void OpenGLWidget::paintGL()
{
if(m_volData)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer
glMatrixMode(GL_MODELVIEW); // Select The Model View Matrix
glLoadIdentity(); // Reset The Current Modelview Matrix
//Moves the camera back so we can see the volume
glTranslatef(0.0f, 0.0f, -m_volData->getDiagonalLength());
glRotatef(m_xRotation, 1.0f, 0.0f, 0.0f);
glRotatef(m_yRotation, 0.0f, 1.0f, 0.0f);
//Centre the volume on the origin
glTranslatef(-g_uVolumeSideLength/2,-g_uVolumeSideLength/2,-g_uVolumeSideLength/2);
for(uint16_t uRegionZ = 0; uRegionZ < m_uVolumeDepthInRegions; ++uRegionZ)
{
for(uint16_t uRegionY = 0; uRegionY < m_uVolumeHeightInRegions; ++uRegionY)
{
for(uint16_t uRegionX = 0; uRegionX < m_uVolumeWidthInRegions; ++uRegionX)
{
Vector3DUint8 v3dRegPos(uRegionX,uRegionY,uRegionZ);
if(m_mapSurfaceMeshes.find(v3dRegPos) != m_mapSurfaceMeshes.end())
{
std::shared_ptr< SurfaceMesh<PositionMaterialNormal> > meshCurrent = m_mapSurfaceMeshes[v3dRegPos];
unsigned int uLodLevel = 0; //meshCurrent->m_vecLodRecords.size() - 1;
if(m_bUseOpenGLVertexBufferObjects)
{
renderRegionVertexBufferObject(m_mapOpenGLSurfaceMeshes[v3dRegPos], uLodLevel);
}
else
{
renderRegionImmediateMode(*meshCurrent, uLodLevel);
}
}
}
}
}
GLenum errCode;
const GLubyte *errString;
if ((errCode = glGetError()) != GL_NO_ERROR)
{
errString = gluErrorString(errCode);
cout << "OpenGL Error: " << errString << endl;
}
}
}
void OpenGLWidget::mousePressEvent(QMouseEvent* event)
{
m_CurrentMousePos = event->pos();
m_LastFrameMousePos = m_CurrentMousePos;
}
void OpenGLWidget::mouseMoveEvent(QMouseEvent* event)
{
m_CurrentMousePos = event->pos();
QPoint diff = m_CurrentMousePos - m_LastFrameMousePos;
m_xRotation += diff.x();
m_yRotation += diff.y();
m_LastFrameMousePos = m_CurrentMousePos;;
}
void OpenGLWidget::setupProjectionMatrix(void)
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
float frustumSize = m_volData->getDiagonalLength() / 2.0f;
float aspect = static_cast<float>(width()) / static_cast<float>(height());
glOrtho(frustumSize*aspect, -frustumSize*aspect, frustumSize, -frustumSize, 1.0, 5000);
}

View File

@ -1,99 +0,0 @@
/*******************************************************************************
Copyright (c) 2005-2009 David Williams
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*******************************************************************************/
#ifndef __PolyVox_OpenGLWidget_H__
#define __PolyVox_OpenGLWidget_H__
#include "glew/glew.h"
#include <QGLWidget>
#include <QTimer>
#include "PolyVoxCore/LargeVolume.h"
#include "PolyVoxCore/SurfaceMesh.h"
#include "PolyVoxCore/Impl/Utility.h"
#include "OpenGLImmediateModeSupport.h"
#include "OpenGLVertexBufferObjectSupport.h"
#include "Shapes.h"
const int32_t g_uVolumeSideLength = 128;
struct Vector3DUint8Compare
{
bool operator() (const PolyVox::Vector3DUint8& a, const PolyVox::Vector3DUint8& b) const
{
const uint32_t size = 3;
for(uint32_t ct = 0; ct < size; ++ct)
{
if (a.getElement(ct) < b.getElement(ct))
return true;
if (b.getElement(ct) < a.getElement(ct))
return false;
}
return false;
}
};
class OpenGLWidget : public QGLWidget
{
public:
OpenGLWidget(QWidget *parent);
void setVolume(PolyVox::LargeVolume<PolyVox::MaterialDensityPair44>* volData);
void mouseMoveEvent(QMouseEvent* event);
void mousePressEvent(QMouseEvent* event);
protected:
void initializeGL();
void resizeGL(int w, int h);
void paintGL();
private:
void setupProjectionMatrix(void);
QPoint m_LastFrameMousePos;
QPoint m_CurrentMousePos;
int m_xRotation;
int m_yRotation;
QTimer *timer;
bool m_bUseOpenGLVertexBufferObjects;
//Creates a volume 128x128x128
PolyVox::LargeVolume<PolyVox::MaterialDensityPair44>* m_volData;
//Rather than storing one big mesh, the volume is broken into regions and a mesh is stored for each region
std::map<PolyVox::Vector3DUint8, OpenGLSurfaceMesh, Vector3DUint8Compare> m_mapOpenGLSurfaceMeshes;
std::map<PolyVox::Vector3DUint8, std::shared_ptr<PolyVox::SurfaceMesh<PolyVox::PositionMaterialNormal> >, Vector3DUint8Compare> m_mapSurfaceMeshes;
unsigned int m_uRegionSideLength;
unsigned int m_uVolumeWidthInRegions;
unsigned int m_uVolumeHeightInRegions;
unsigned int m_uVolumeDepthInRegions;
};
#endif //__PolyVox_OpenGLWidget_H__

View File

@ -1,73 +1,73 @@
/*******************************************************************************
Copyright (c) 2005-2009 David Williams
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*******************************************************************************/
#include "Shapes.h"
#include "PolyVoxCore/MaterialDensityPair.h"
using namespace PolyVox;
void createSphereInVolume(LargeVolume<MaterialDensityPair44>& volData, float fRadius, uint8_t uValue)
{
//This vector hold the position of the center of the volume
Vector3DInt32 v3dVolCenter = (volData.getEnclosingRegion().getUpperCorner() - volData.getEnclosingRegion().getLowerCorner()) / static_cast<int32_t>(2);
//This three-level for loop iterates over every voxel in the volume
for (int z = 0; z < volData.getDepth(); z++)
{
for (int y = 0; y < volData.getHeight(); y++)
{
for (int x = 0; x < volData.getWidth(); x++)
{
//Store our current position as a vector...
Vector3DInt32 v3dCurrentPos(x,y,z);
//And compute how far the current position is from the center of the volume
double fDistToCenter = (v3dCurrentPos - v3dVolCenter).length();
//If the current voxel is less than 'radius' units from the center
//then we make it solid, otherwise we make it empty space.
if(fDistToCenter <= fRadius)
{
volData.setVoxelAt(x,y,z, MaterialDensityPair44(uValue, uValue > 0 ? MaterialDensityPair44::getMaxDensity() : MaterialDensityPair44::getMinDensity()));
}
}
}
}
}
void createCubeInVolume(LargeVolume<MaterialDensityPair44>& volData, Vector3DInt32 lowerCorner, Vector3DInt32 upperCorner, uint8_t uValue)
{
uint8_t maxDen = MaterialDensityPair44::getMaxDensity();
uint8_t minDen = MaterialDensityPair44::getMinDensity();
//This three-level for loop iterates over every voxel between the specified corners
for (int z = lowerCorner.getZ(); z <= upperCorner.getZ(); z++)
{
for (int y = lowerCorner.getY(); y <= upperCorner.getY(); y++)
{
for (int x = lowerCorner.getX() ; x <= upperCorner.getX(); x++)
{
volData.setVoxelAt(x,y,z, MaterialDensityPair44(uValue, uValue > 0 ? maxDen : minDen));
}
}
}
/*******************************************************************************
Copyright (c) 2005-2009 David Williams
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*******************************************************************************/
#include "Shapes.h"
#include "PolyVox/MaterialDensityPair.h"
using namespace PolyVox;
void createSphereInVolume(PagedVolume<MaterialDensityPair88>& volData, float fRadius, uint8_t uValue)
{
//This vector hold the position of the center of the volume
Vector3DInt32 v3dVolCenter = (volData.getEnclosingRegion().getUpperCorner() - volData.getEnclosingRegion().getLowerCorner()) / static_cast<int32_t>(2);
//This three-level for loop iterates over every voxel in the volume
for (int z = 0; z < volData.getDepth(); z++)
{
for (int y = 0; y < volData.getHeight(); y++)
{
for (int x = 0; x < volData.getWidth(); x++)
{
//Store our current position as a vector...
Vector3DInt32 v3dCurrentPos(x,y,z);
//And compute how far the current position is from the center of the volume
double fDistToCenter = (v3dCurrentPos - v3dVolCenter).length();
//If the current voxel is less than 'radius' units from the center
//then we make it solid, otherwise we make it empty space.
if(fDistToCenter <= fRadius)
{
volData.setVoxelAt(x,y,z, MaterialDensityPair88(uValue, uValue > 0 ? MaterialDensityPair88::getMaxDensity() : MaterialDensityPair88::getMinDensity()));
}
}
}
}
}
void createCubeInVolume(PagedVolume<MaterialDensityPair88>& volData, Vector3DInt32 lowerCorner, Vector3DInt32 upperCorner, uint8_t uValue)
{
uint8_t maxDen = MaterialDensityPair88::getMaxDensity();
uint8_t minDen = MaterialDensityPair88::getMinDensity();
//This three-level for loop iterates over every voxel between the specified corners
for (int z = lowerCorner.getZ(); z <= upperCorner.getZ(); z++)
{
for (int y = lowerCorner.getY(); y <= upperCorner.getY(); y++)
{
for (int x = lowerCorner.getX() ; x <= upperCorner.getX(); x++)
{
volData.setVoxelAt(x,y,z, MaterialDensityPair88(uValue, uValue > 0 ? maxDen : minDen));
}
}
}
}

View File

@ -1,33 +1,33 @@
/*******************************************************************************
Copyright (c) 2005-2009 David Williams
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*******************************************************************************/
#ifndef __OpenGLExample_Shapes_H__
#define __OpenGLExample_Shapes_H__
#include "PolyVoxCore/LargeVolume.h"
#include "PolyVoxCore/MaterialDensityPair.h"
void createSphereInVolume(PolyVox::LargeVolume<PolyVox::MaterialDensityPair44>& volData, float fRadius, uint8_t uValue);
void createCubeInVolume(PolyVox::LargeVolume<PolyVox::MaterialDensityPair44>& volData, PolyVox::Vector3DInt32 lowerCorner, PolyVox::Vector3DInt32 upperCorner, uint8_t uValue);
/*******************************************************************************
Copyright (c) 2005-2009 David Williams
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*******************************************************************************/
#ifndef __OpenGLExample_Shapes_H__
#define __OpenGLExample_Shapes_H__
#include "PolyVox/PagedVolume.h"
#include "PolyVox/MaterialDensityPair.h"
void createSphereInVolume(PolyVox::LargeVolume<PolyVox::MaterialDensityPair88>& volData, float fRadius, uint8_t uValue);
void createCubeInVolume(PolyVox::LargeVolume<PolyVox::MaterialDensityPair88>& volData, PolyVox::Vector3DInt32 lowerCorner, PolyVox::Vector3DInt32 upperCorner, uint8_t uValue);
#endif //__OpenGLExample_Shapes_H__

View File

@ -1,107 +1,146 @@
/*******************************************************************************
Copyright (c) 2005-2009 David Williams
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*******************************************************************************/
#include "PolyVoxCore/FilePager.h"
#include "PolyVoxCore/MaterialDensityPair.h"
#include "PolyVoxCore/LargeVolume.h"
#include "PolyVoxCore/LowPassFilter.h"
#include "PolyVoxCore/RawVolume.h"
#include "PolyVoxCore/RLEBlockCompressor.h"
#include "PolyVoxCore/SurfaceMesh.h"
#include "PolyVoxCore/Impl/Utility.h"
#include "OpenGLImmediateModeSupport.h"
#include "OpenGLVertexBufferObjectSupport.h"
#include "Shapes.h"
#include "OpenGLWidget.h"
#ifdef WIN32
#include <windows.h> // Standard Header For Most Programs
#endif
#include <QApplication>
#include <QTime>
//Some namespaces we need
using namespace std;
using namespace PolyVox;
using namespace std;
int main(int argc, char *argv[])
{
RLEBlockCompressor<MaterialDensityPair44>* compressor = new RLEBlockCompressor<MaterialDensityPair44>();
FilePager<MaterialDensityPair44>* pager = new FilePager<MaterialDensityPair44>("./");
LargeVolume<MaterialDensityPair44> volData(PolyVox::Region(Vector3DInt32(0,0,0), Vector3DInt32(g_uVolumeSideLength-1, g_uVolumeSideLength-1, g_uVolumeSideLength-1)), compressor, pager);
//Make our volume contain a sphere in the center.
int32_t minPos = 0;
int32_t midPos = g_uVolumeSideLength / 2;
int32_t maxPos = g_uVolumeSideLength - 1;
cout << "Creating sphere 1" << std::endl;
createSphereInVolume(volData, 60.0f, 5);
cout << "Creating sphere 2" << std::endl;
createSphereInVolume(volData, 50.0f, 4);
cout << "Creating sphere 3" << std::endl;
createSphereInVolume(volData, 40.0f, 3);
cout << "Creating sphere 4" << std::endl;
createSphereInVolume(volData, 30.0f, 2);
cout << "Creating sphere 5" << std::endl;
createSphereInVolume(volData, 20.0f, 1);
cout << "Creating cubes" << std::endl;
createCubeInVolume(volData, Vector3DInt32(minPos, minPos, minPos), Vector3DInt32(midPos-1, midPos-1, midPos-1), 0);
createCubeInVolume(volData, Vector3DInt32(midPos+1, midPos+1, minPos), Vector3DInt32(maxPos, maxPos, midPos-1), 0);
createCubeInVolume(volData, Vector3DInt32(midPos+1, minPos, midPos+1), Vector3DInt32(maxPos, midPos-1, maxPos), 0);
createCubeInVolume(volData, Vector3DInt32(minPos, midPos+1, midPos+1), Vector3DInt32(midPos-1, maxPos, maxPos), 0);
createCubeInVolume(volData, Vector3DInt32(1, midPos-10, midPos-10), Vector3DInt32(maxPos-1, midPos+10, midPos+10), MaterialDensityPair44::getMaxDensity());
createCubeInVolume(volData, Vector3DInt32(midPos-10, 1, midPos-10), Vector3DInt32(midPos+10, maxPos-1, midPos+10), MaterialDensityPair44::getMaxDensity());
createCubeInVolume(volData, Vector3DInt32(midPos-10, midPos-10 ,1), Vector3DInt32(midPos+10, midPos+10, maxPos-1), MaterialDensityPair44::getMaxDensity());
//I've removed this smoothing because it doesn't really make sense to apply a low pass filter to a volume with material values.
//I could implement the mathematical operators for MaterialDensityPair in such a way that they ignores the materials but this
//seems to be setting a bad example. Users can add this operators in their own classes if they want smoothing.
//RawVolume<MaterialDensityPair44> tempVolume(PolyVox::Region(0,0,0,128, 128, 128));
//LowPassFilter< LargeVolume<MaterialDensityPair44>, RawVolume<MaterialDensityPair44> > pass1(&volData, PolyVox::Region(Vector3DInt32(62, 62, 62), Vector3DInt32(126, 126, 126)), &tempVolume, PolyVox::Region(Vector3DInt32(62, 62, 62), Vector3DInt32(126, 126, 126)), 3);
//pass1.executeSAT();
//LowPassFilter< RawVolume<MaterialDensityPair44>, LargeVolume<MaterialDensityPair44> > pass2(&tempVolume, PolyVox::Region(Vector3DInt32(62, 62, 62), Vector3DInt32(126, 126, 126)), &volData, PolyVox::Region(Vector3DInt32(62, 62, 62), Vector3DInt32(126, 126, 126)), 3);
//pass2.executeSAT();
QApplication app(argc, argv);
OpenGLWidget openGLWidget(0);
openGLWidget.show();
QTime time;
time.start();
openGLWidget.setVolume(&volData);
cout << endl << "Time taken = " << time.elapsed() / 1000.0f << "s" << endl << endl;
//return 0;
return app.exec();
}
/*******************************************************************************
Copyright (c) 2005-2009 David Williams
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*******************************************************************************/
#include "PolyVox/FilePager.h"
#include "PolyVox/MarchingCubesSurfaceExtractor.h"
#include "PolyVox/MaterialDensityPair.h"
#include "PolyVox/LowPassFilter.h"
#include "PolyVox/RawVolume.h"
#include "PolyVox/Mesh.h"
#include "PolyVox/Impl/Utility.h"
#include "Shapes.h"
#include "OpenGLWidget.h"
#ifdef WIN32
#include <windows.h> // Standard Header For Most Programs
#endif
#include <QApplication>
#include <QTime>
//Some namespaces we need
using namespace std;
using namespace PolyVox;
using namespace std;
const int32_t g_uVolumeSideLength = 128;
int main(int argc, char *argv[])
{
FilePager<MaterialDensityPair88>* pager = new FilePager<MaterialDensityPair88>(".");
PagedVolume<MaterialDensityPair88> volData(PolyVox::Region(Vector3DInt32(0, 0, 0), Vector3DInt32(g_uVolumeSideLength - 1, g_uVolumeSideLength - 1, g_uVolumeSideLength - 1)), pager);
//Make our volume contain a sphere in the center.
int32_t minPos = 0;
int32_t midPos = g_uVolumeSideLength / 2;
int32_t maxPos = g_uVolumeSideLength - 1;
cout << "Creating sphere 1" << std::endl;
createSphereInVolume(volData, 60.0f, 5);
cout << "Creating sphere 2" << std::endl;
createSphereInVolume(volData, 50.0f, 4);
cout << "Creating sphere 3" << std::endl;
createSphereInVolume(volData, 40.0f, 3);
cout << "Creating sphere 4" << std::endl;
createSphereInVolume(volData, 30.0f, 2);
cout << "Creating sphere 5" << std::endl;
createSphereInVolume(volData, 20.0f, 1);
cout << "Creating cubes" << std::endl;
createCubeInVolume(volData, Vector3DInt32(minPos, minPos, minPos), Vector3DInt32(midPos-1, midPos-1, midPos-1), 0);
createCubeInVolume(volData, Vector3DInt32(midPos+1, midPos+1, minPos), Vector3DInt32(maxPos, maxPos, midPos-1), 0);
createCubeInVolume(volData, Vector3DInt32(midPos+1, minPos, midPos+1), Vector3DInt32(maxPos, midPos-1, maxPos), 0);
createCubeInVolume(volData, Vector3DInt32(minPos, midPos+1, midPos+1), Vector3DInt32(midPos-1, maxPos, maxPos), 0);
createCubeInVolume(volData, Vector3DInt32(1, midPos-10, midPos-10), Vector3DInt32(maxPos-1, midPos+10, midPos+10), MaterialDensityPair44::getMaxDensity());
createCubeInVolume(volData, Vector3DInt32(midPos-10, 1, midPos-10), Vector3DInt32(midPos+10, maxPos-1, midPos+10), MaterialDensityPair44::getMaxDensity());
createCubeInVolume(volData, Vector3DInt32(midPos-10, midPos-10 ,1), Vector3DInt32(midPos+10, midPos+10, maxPos-1), MaterialDensityPair44::getMaxDensity());
QApplication app(argc, argv);
OpenGLWidget openGLWidget(0);
openGLWidget.show();
QSharedPointer<QGLShaderProgram> shader(new QGLShaderProgram);
if (!shader->addShaderFromSourceFile(QGLShader::Vertex, ":/openglexample.vert"))
{
std::cerr << shader->log().toStdString() << std::endl;
exit(EXIT_FAILURE);
}
if (!shader->addShaderFromSourceFile(QGLShader::Fragment, ":/openglexample.frag"))
{
std::cerr << shader->log().toStdString() << std::endl;
exit(EXIT_FAILURE);
}
openGLWidget.setShader(shader);
QTime time;
time.start();
//openGLWidget.setVolume(&volData);
cout << endl << "Time taken = " << time.elapsed() / 1000.0f << "s" << endl << endl;
const int32_t extractedRegionSize = 32;
int meshCounter = 0;
for (int32_t z = 0; z < volData.getDepth(); z += extractedRegionSize)
{
for (int32_t y = 0; y < volData.getHeight(); y += extractedRegionSize)
{
for (int32_t x = 0; x < volData.getWidth(); x += extractedRegionSize)
{
// Specify the region to extract based on a starting position and the desired region sze.
PolyVox::Region regToExtract(x, y, z, x + extractedRegionSize, y + extractedRegionSize, z + extractedRegionSize);
// If you uncomment this line you will be able to see that the volume is rendered as multiple seperate meshes.
//regToExtract.shrink(1);
// Perform the extraction for this region of the volume
auto mesh = extractMarchingCubesMesh(&volData, regToExtract);
// The returned mesh needs to be decoded to be appropriate for GPU rendering.
auto decodedMesh = decodeMesh(mesh);
// Pass the surface to the OpenGL window. Note that we are also passing an offset in this multi-mesh example. This is because
// the surface extractors return a mesh with 'local space' positions to reduce storage requirements and precision problems.
openGLWidget.addMesh(decodedMesh, decodedMesh.getOffset());
meshCounter++;
}
}
}
cout << "Rendering volume as " << meshCounter << " seperate meshes" << endl;
openGLWidget.setViewableRegion(volData.getEnclosingRegion());
return app.exec();
}

View File

@ -0,0 +1,45 @@
#version 130
in vec4 worldPosition; //Passed in from the vertex shader
in vec3 normalFromVS;
flat in ivec2 materialFromVS;
out vec4 outputColor;
void main()
{
// The first byte of our voxel data is the material.
// We use this to decide how to color the fragment.
vec4 surfaceColor;
switch(materialFromVS.x)
{
case 1:
surfaceColor = vec4(1.0, 0.0, 0.0, 1.0);
break;
case 2:
surfaceColor = vec4(0.0, 1.0, 0.0, 1.0);
break;
case 3:
surfaceColor = vec4(0.0, 0.0, 1.0, 1.0);
break;
case 4:
surfaceColor = vec4(1.0, 1.0, 0.0, 1.0);
break;
case 5:
surfaceColor = vec4(1.0, 0.0, 1.0, 1.0);
break;
default:
surfaceColor = vec4(1.0, 1.0, 1.0, 1.0);
break;
}
// Quick and dirty lighting, obviously a real implementation
// should pass light properties as shader parameters, etc.
vec3 lightDir = vec3(0.0, 0.0, 1.0);
float diffuse = clamp(dot(lightDir, normalFromVS), 0.0, 1.0);
diffuse *= 0.7; // Dim the diffuse a bit
float ambient = 0.3; // Add some ambient
float lightIntensity = diffuse + ambient; // Compute the final light intensity
outputColor = surfaceColor * lightIntensity; //Compute final rendered color
}

View File

@ -0,0 +1,6 @@
<!DOCTYPE RCC><RCC version="1.0">
<qresource>
<file>openglexample.vert</file>
<file>openglexample.frag</file>
</qresource>
</RCC>

View File

@ -0,0 +1,26 @@
#version 140
in vec4 position; // This will be the position of the vertex in model-space
in vec4 normal; // The normal data may not have been set
in ivec2 material;
uniform mat4 cameraToClipMatrix;
uniform mat4 worldToCameraMatrix;
uniform mat4 modelToWorldMatrix;
out vec4 worldPosition; //This is being passed to the fragment shader to calculate the normals
out vec3 normalFromVS;
flat out ivec2 materialFromVS;
void main()
{
// Compute the usual OpenGL transformation to clip space.
gl_Position = cameraToClipMatrix * worldToCameraMatrix * modelToWorldMatrix * position;
// This example is demonstrating the marching cubes mesh, which does have per-vertex normals. We can
// just pass them through, though real code might want to deal with transforming normals appropriatly.
normalFromVS = normal.xyz;
// Nothing special here, we just pass the material through to the fragment shader.
materialFromVS = material;
}

View File

@ -1,73 +1,71 @@
# Copyright (c) 2010-2012 David Williams
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.
#
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
#
# 1. The origin of this software must not be misrepresented; you must not
# claim that you wrote the original software. If you use this software
# in a product, an acknowledgment in the product documentation would be
# appreciated but is not required.
#
# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.
#
# 3. This notice may not be removed or altered from any source
# distribution.
PROJECT(PagingExample)
#Projects source files
SET(SRC_FILES
main.cpp
OpenGLWidget.cpp
Perlin.cpp
)
#Projects headers files
SET(INC_FILES
OpenGLWidget.h
Perlin.h
)
add_definitions(-DGLEW_STATIC)
#"Sources" and "Headers" are the group names in Visual Studio.
#They may have other uses too...
SOURCE_GROUP("Sources" FILES ${SRC_FILES})
SOURCE_GROUP("Headers" FILES ${INC_FILES})
FIND_PACKAGE(OpenGL REQUIRED)
#Tell CMake the paths for OpenGL and for PolyVox (which is just relative to our current location)
INCLUDE_DIRECTORIES(${OPENGL_INCLUDE_DIR} ${PolyVoxCore_BINARY_DIR}/include ${PolyVoxCore_SOURCE_DIR}/include ${GLEW_SOURCE_DIR})
LINK_DIRECTORIES(${PolyVoxCore_BINARY_DIR})
#Build
ADD_EXECUTABLE(PagingExample ${SRC_FILES})
IF(MSVC)
SET_TARGET_PROPERTIES(PagingExample PROPERTIES COMPILE_FLAGS "/W4 /wd4127")
ENDIF(MSVC)
TARGET_LINK_LIBRARIES(PagingExample glew Qt5::OpenGL ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY} PolyVoxCore)
SET_PROPERTY(TARGET PagingExample PROPERTY FOLDER "Examples")
#Install - Only install the example in Windows
IF(WIN32)
INSTALL(TARGETS PagingExample
RUNTIME DESTINATION Examples/OpenGL/bin
LIBRARY DESTINATION Examples/OpenGL/lib
ARCHIVE DESTINATION Examples/OpenGL/lib
COMPONENT example
)
#.dlls should be installed in shared builds.
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../release/PolyVoxCore.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Release)
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../release/PolyVoxUtil.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Release)
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../debug/PolyVoxCore.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Debug)
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../debug/PolyVoxUtil.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Debug)
ENDIF(WIN32)
# Copyright (c) 2010-2012 David Williams
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.
#
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
#
# 1. The origin of this software must not be misrepresented; you must not
# claim that you wrote the original software. If you use this software
# in a product, an acknowledgment in the product documentation would be
# appreciated but is not required.
#
# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.
#
# 3. This notice may not be removed or altered from any source
# distribution.
CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
PROJECT(PagingExample)
#Projects source files
SET(SRC_FILES
main.cpp
../common/OpenGLWidget.cpp
Perlin.cpp
)
#Projects headers files
SET(INC_FILES
OpenGLWidget.h
Perlin.h
)
add_definitions(-DGLEW_STATIC)
FIND_PACKAGE(OpenGL REQUIRED)
#Tell CMake the paths for OpenGL and for PolyVox (which is just relative to our current location)
INCLUDE_DIRECTORIES(${OPENGL_INCLUDE_DIR} ${PolyVoxHeaders_SOURCE_DIR} ${GLEW_SOURCE_DIR})
#This will include the shader files inside the compiled binary
QT4_ADD_RESOURCES(COMMON_RESOURCES_RCC ../common/example.qrc)
# Put the resources in a seperate folder in Visual Studio
SOURCE_GROUP("Resource Files" FILES ../common/example.qrc ${COMMON_RESOURCES_RCC})
#Build
ADD_EXECUTABLE(PagingExample ${SRC_FILES} ${COMMON_RESOURCES_RCC})
IF(MSVC)
SET_TARGET_PROPERTIES(PagingExample PROPERTIES COMPILE_FLAGS "/W4 /wd4127")
ENDIF(MSVC)
TARGET_LINK_LIBRARIES(PagingExample glew ${QT_LIBRARIES} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY})
SET_PROPERTY(TARGET PagingExample PROPERTY FOLDER "Examples")
configure_file(../common/example.vert example.vert COPYONLY)
configure_file(../common/example.frag example.frag COPYONLY)
#Install - Only install the example in Windows
IF(WIN32)
INSTALL(TARGETS PagingExample
RUNTIME DESTINATION Examples/OpenGL/bin
LIBRARY DESTINATION Examples/OpenGL/lib
ARCHIVE DESTINATION Examples/OpenGL/lib
COMPONENT example
)
ENDIF(WIN32)

View File

@ -1,135 +0,0 @@
#include "OpenGLWidget.h"
#include <QMouseEvent>
using namespace PolyVox;
using namespace std;
OpenGLWidget::OpenGLWidget(QWidget *parent)
:QGLWidget(parent)
,m_uBeginIndex(0)
,m_uEndIndex(0)
,noOfIndices(0)
,m_xRotation(0)
,m_yRotation(0)
{
}
void OpenGLWidget::setSurfaceMeshToRender(const PolyVox::SurfaceMesh<PositionMaterialNormal>& surfaceMesh)
{
if((surfaceMesh.getNoOfIndices() == 0) || (surfaceMesh.getNoOfVertices() == 0))
{
//We don't have a valid mesh
return;
}
//Convienient access to the vertices and indices
const vector<uint32_t>& vecIndices = surfaceMesh.getIndices();
const vector<PositionMaterialNormal>& vecVertices = surfaceMesh.getVertices();
//Build an OpenGL index buffer
glGenBuffers(1, &indexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
const GLvoid* pIndices = static_cast<const GLvoid*>(&(vecIndices[0]));
glBufferData(GL_ELEMENT_ARRAY_BUFFER, vecIndices.size() * sizeof(uint32_t), pIndices, GL_STATIC_DRAW);
//Build an OpenGL vertex buffer
glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
const GLvoid* pVertices = static_cast<const GLvoid*>(&(vecVertices[0]));
glBufferData(GL_ARRAY_BUFFER, vecVertices.size() * sizeof(PositionMaterialNormal), pVertices, GL_STATIC_DRAW);
m_uBeginIndex = 0;
m_uEndIndex = vecIndices.size();
noOfIndices = surfaceMesh.getNoOfIndices();
}
void OpenGLWidget::initializeGL()
{
//We need GLEW to access recent OpenGL functionality
GLenum err = glewInit();
if (GLEW_OK != err)
{
/* Problem: glewInit failed, something is seriously wrong. */
std::cout << "GLEW Error: " << glewGetErrorString(err) << std::endl;
}
//Set up the clear colour
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClearDepth(1.0f);
//Enable the depth buffer
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
//Anable smooth lighting
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glShadeModel(GL_SMOOTH);
//We'll be rendering with index/vertex arrays
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
}
void OpenGLWidget::resizeGL(int w, int h)
{
//Setup the viewport
glViewport(0, 0, w, h);
//Set up the projection matrix
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
float frustumSize = 128.0f * 1.7f; //Half the volume diagonal
float aspect = static_cast<float>(width()) / static_cast<float>(height());
glOrtho(frustumSize*aspect, -frustumSize*aspect, frustumSize, -frustumSize, 10.0, 10000);
}
void OpenGLWidget::paintGL()
{
if(noOfIndices == 0)
{
//Nothing to render
return;
}
//Clear the screen
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//Set up the viewing transformation
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0f,0.0f,-5000.0f); //Centre volume and move back
glRotatef(m_xRotation, 1.0f, 0.0f, 0.0f);
glRotatef(m_yRotation, 0.0f, 1.0f, 0.0f);
glTranslatef(-128.0f,-128.0f,-128.0f); //Centre volume and move back
//Bind the index buffer
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
//Bind the vertex buffer
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glVertexPointer(3, GL_FLOAT, sizeof(PositionMaterialNormal), 0);
glNormalPointer(GL_FLOAT, sizeof(PositionMaterialNormal), (GLvoid*)12);
glDrawRangeElements(GL_TRIANGLES, m_uBeginIndex, m_uEndIndex-1, m_uEndIndex - m_uBeginIndex, GL_UNSIGNED_INT, 0);
}
void OpenGLWidget::mousePressEvent(QMouseEvent* event)
{
m_CurrentMousePos = event->pos();
m_LastFrameMousePos = m_CurrentMousePos;
update();
}
void OpenGLWidget::mouseMoveEvent(QMouseEvent* event)
{
m_CurrentMousePos = event->pos();
QPoint diff = m_CurrentMousePos - m_LastFrameMousePos;
m_xRotation += diff.x();
m_yRotation += diff.y();
m_LastFrameMousePos = m_CurrentMousePos;
update();
}

View File

@ -1,67 +0,0 @@
/*******************************************************************************
Copyright (c) 2005-2009 David Williams
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*******************************************************************************/
#ifndef __BasicExample_OpenGLWidget_H__
#define __BasicExample_OpenGLWidget_H__
#include "PolyVoxCore/SurfaceMesh.h"
#include "glew/glew.h"
#include <QGLWidget>
class OpenGLWidget : public QGLWidget
{
public:
//Constructor
OpenGLWidget(QWidget *parent);
//Mouse handling
void mouseMoveEvent(QMouseEvent* event);
void mousePressEvent(QMouseEvent* event);
//Convert a SrfaceMesh to OpenGL index/vertex buffers
void setSurfaceMeshToRender(const PolyVox::SurfaceMesh<PolyVox::PositionMaterialNormal>& surfaceMesh);
protected:
//Qt OpenGL functions
void initializeGL();
void resizeGL(int w, int h);
void paintGL();
private:
//Index/vertex buffer data
GLuint m_uBeginIndex;
GLuint m_uEndIndex;
GLuint noOfIndices;
GLuint indexBuffer;
GLuint vertexBuffer;
//Mouse data
QPoint m_LastFrameMousePos;
QPoint m_CurrentMousePos;
int m_xRotation;
int m_yRotation;
};
#endif //__BasicExample_OpenGLWidget_H__

View File

@ -1,265 +1,265 @@
// Code from http://www.flipcode.com/archives/Perlin_Noise_Class.shtml
// This is only in PolyVox for the purpose of the examples. It was not written by
// the PolyVox authors and cannot be assumed to be under the same license as PolyVox.
/* coherent noise function over 1, 2 or 3 dimensions */
/* (copyright Ken Perlin) */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "Perlin.h"
#define B SAMPLE_SIZE
#define BM (SAMPLE_SIZE-1)
#define N 0x1000
#define NP 12 /* 2^N */
#define NM 0xfff
#define s_curve(t) ( t * t * (3.0f - 2.0f * t) )
#define lerp(t, a, b) ( a + t * (b - a) )
#define setup(i,b0,b1,r0,r1)\
t = vec[i] + N;\
b0 = ((int)t) & BM;\
b1 = (b0+1) & BM;\
r0 = t - (int)t;\
r1 = r0 - 1.0f;
float Perlin::noise1(float arg)
{
int bx0, bx1;
float rx0, rx1, sx, t, u, v, vec[1];
vec[0] = arg;
if (mStart)
{
srand(mSeed);
mStart = false;
init();
}
setup(0, bx0,bx1, rx0,rx1);
sx = s_curve(rx0);
u = rx0 * g1[ p[ bx0 ] ];
v = rx1 * g1[ p[ bx1 ] ];
return lerp(sx, u, v);
}
float Perlin::noise2(float vec[2])
{
int bx0, bx1, by0, by1, b00, b10, b01, b11;
float rx0, rx1, ry0, ry1, *q, sx, sy, a, b, t, u, v;
int i, j;
if (mStart)
{
srand(mSeed);
mStart = false;
init();
}
setup(0,bx0,bx1,rx0,rx1);
setup(1,by0,by1,ry0,ry1);
i = p[bx0];
j = p[bx1];
b00 = p[i + by0];
b10 = p[j + by0];
b01 = p[i + by1];
b11 = p[j + by1];
sx = s_curve(rx0);
sy = s_curve(ry0);
#define at2(rx,ry) ( rx * q[0] + ry * q[1] )
q = g2[b00];
u = at2(rx0,ry0);
q = g2[b10];
v = at2(rx1,ry0);
a = lerp(sx, u, v);
q = g2[b01];
u = at2(rx0,ry1);
q = g2[b11];
v = at2(rx1,ry1);
b = lerp(sx, u, v);
return lerp(sy, a, b);
}
float Perlin::noise3(float vec[3])
{
int bx0, bx1, by0, by1, bz0, bz1, b00, b10, b01, b11;
float rx0, rx1, ry0, ry1, rz0, rz1, *q, sy, sz, a, b, c, d, t, u, v;
int i, j;
if (mStart)
{
srand(mSeed);
mStart = false;
init();
}
setup(0, bx0,bx1, rx0,rx1);
setup(1, by0,by1, ry0,ry1);
setup(2, bz0,bz1, rz0,rz1);
i = p[ bx0 ];
j = p[ bx1 ];
b00 = p[ i + by0 ];
b10 = p[ j + by0 ];
b01 = p[ i + by1 ];
b11 = p[ j + by1 ];
t = s_curve(rx0);
sy = s_curve(ry0);
sz = s_curve(rz0);
#define at3(rx,ry,rz) ( rx * q[0] + ry * q[1] + rz * q[2] )
q = g3[ b00 + bz0 ] ; u = at3(rx0,ry0,rz0);
q = g3[ b10 + bz0 ] ; v = at3(rx1,ry0,rz0);
a = lerp(t, u, v);
q = g3[ b01 + bz0 ] ; u = at3(rx0,ry1,rz0);
q = g3[ b11 + bz0 ] ; v = at3(rx1,ry1,rz0);
b = lerp(t, u, v);
c = lerp(sy, a, b);
q = g3[ b00 + bz1 ] ; u = at3(rx0,ry0,rz1);
q = g3[ b10 + bz1 ] ; v = at3(rx1,ry0,rz1);
a = lerp(t, u, v);
q = g3[ b01 + bz1 ] ; u = at3(rx0,ry1,rz1);
q = g3[ b11 + bz1 ] ; v = at3(rx1,ry1,rz1);
b = lerp(t, u, v);
d = lerp(sy, a, b);
return lerp(sz, c, d);
}
void Perlin::normalize2(float v[2])
{
float s;
s = (float)sqrt(v[0] * v[0] + v[1] * v[1]);
s = 1.0f/s;
v[0] = v[0] * s;
v[1] = v[1] * s;
}
void Perlin::normalize3(float v[3])
{
float s;
s = (float)sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
s = 1.0f/s;
v[0] = v[0] * s;
v[1] = v[1] * s;
v[2] = v[2] * s;
}
void Perlin::init(void)
{
int i, j, k;
for (i = 0 ; i < B ; i++)
{
p[i] = i;
g1[i] = (float)((rand() % (B + B)) - B) / B;
for (j = 0 ; j < 2 ; j++)
g2[i][j] = (float)((rand() % (B + B)) - B) / B;
normalize2(g2[i]);
for (j = 0 ; j < 3 ; j++)
g3[i][j] = (float)((rand() % (B + B)) - B) / B;
normalize3(g3[i]);
}
while (--i)
{
k = p[i];
p[i] = p[j = rand() % B];
p[j] = k;
}
for (i = 0 ; i < B + 2 ; i++)
{
p[B + i] = p[i];
g1[B + i] = g1[i];
for (j = 0 ; j < 2 ; j++)
g2[B + i][j] = g2[i][j];
for (j = 0 ; j < 3 ; j++)
g3[B + i][j] = g3[i][j];
}
}
float Perlin::perlin_noise_2D(float vec[2])
{
int terms = mOctaves;
float result = 0.0f;
float amp = mAmplitude;
vec[0]*=mFrequency;
vec[1]*=mFrequency;
for( int i=0; i<terms; i++ )
{
result += noise2(vec)*amp;
vec[0] *= 2.0f;
vec[1] *= 2.0f;
amp*=0.5f;
}
return result;
}
float Perlin::perlin_noise_3D(float vec[3])
{
int terms = mOctaves;
float result = 0.0f;
float amp = mAmplitude;
vec[0]*=mFrequency;
vec[1]*=mFrequency;
vec[2]*=mFrequency;
for( int i=0; i<terms; i++ )
{
result += noise3(vec)*amp;
vec[0] *= 2.0f;
vec[1] *= 2.0f;
vec[2] *= 2.0f;
amp*=0.5f;
}
return result;
}
Perlin::Perlin(int octaves,float freq,float amp,int seed)
{
mOctaves = octaves;
mFrequency = freq;
mAmplitude = amp;
mSeed = seed;
mStart = true;
}
// Code from http://www.flipcode.com/archives/Perlin_Noise_Class.shtml
// This is only in PolyVox for the purpose of the examples. It was not written by
// the PolyVox authors and cannot be assumed to be under the same license as PolyVox.
/* coherent noise function over 1, 2 or 3 dimensions */
/* (copyright Ken Perlin) */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "Perlin.h"
#define B SAMPLE_SIZE
#define BM (SAMPLE_SIZE-1)
#define N 0x1000
#define NP 12 /* 2^N */
#define NM 0xfff
#define s_curve(t) ( t * t * (3.0f - 2.0f * t) )
#define lerp(t, a, b) ( a + t * (b - a) )
#define setup(i,b0,b1,r0,r1)\
t = vec[i] + N;\
b0 = ((int)t) & BM;\
b1 = (b0+1) & BM;\
r0 = t - (int)t;\
r1 = r0 - 1.0f;
float Perlin::noise1(float arg)
{
int bx0, bx1;
float rx0, rx1, sx, t, u, v, vec[1];
vec[0] = arg;
if (mStart)
{
srand(mSeed);
mStart = false;
init();
}
setup(0, bx0,bx1, rx0,rx1);
sx = s_curve(rx0);
u = rx0 * g1[ p[ bx0 ] ];
v = rx1 * g1[ p[ bx1 ] ];
return lerp(sx, u, v);
}
float Perlin::noise2(float vec[2])
{
int bx0, bx1, by0, by1, b00, b10, b01, b11;
float rx0, rx1, ry0, ry1, *q, sx, sy, a, b, t, u, v;
int i, j;
if (mStart)
{
srand(mSeed);
mStart = false;
init();
}
setup(0,bx0,bx1,rx0,rx1);
setup(1,by0,by1,ry0,ry1);
i = p[bx0];
j = p[bx1];
b00 = p[i + by0];
b10 = p[j + by0];
b01 = p[i + by1];
b11 = p[j + by1];
sx = s_curve(rx0);
sy = s_curve(ry0);
#define at2(rx,ry) ( rx * q[0] + ry * q[1] )
q = g2[b00];
u = at2(rx0,ry0);
q = g2[b10];
v = at2(rx1,ry0);
a = lerp(sx, u, v);
q = g2[b01];
u = at2(rx0,ry1);
q = g2[b11];
v = at2(rx1,ry1);
b = lerp(sx, u, v);
return lerp(sy, a, b);
}
float Perlin::noise3(float vec[3])
{
int bx0, bx1, by0, by1, bz0, bz1, b00, b10, b01, b11;
float rx0, rx1, ry0, ry1, rz0, rz1, *q, sy, sz, a, b, c, d, t, u, v;
int i, j;
if (mStart)
{
srand(mSeed);
mStart = false;
init();
}
setup(0, bx0,bx1, rx0,rx1);
setup(1, by0,by1, ry0,ry1);
setup(2, bz0,bz1, rz0,rz1);
i = p[ bx0 ];
j = p[ bx1 ];
b00 = p[ i + by0 ];
b10 = p[ j + by0 ];
b01 = p[ i + by1 ];
b11 = p[ j + by1 ];
t = s_curve(rx0);
sy = s_curve(ry0);
sz = s_curve(rz0);
#define at3(rx,ry,rz) ( rx * q[0] + ry * q[1] + rz * q[2] )
q = g3[ b00 + bz0 ] ; u = at3(rx0,ry0,rz0);
q = g3[ b10 + bz0 ] ; v = at3(rx1,ry0,rz0);
a = lerp(t, u, v);
q = g3[ b01 + bz0 ] ; u = at3(rx0,ry1,rz0);
q = g3[ b11 + bz0 ] ; v = at3(rx1,ry1,rz0);
b = lerp(t, u, v);
c = lerp(sy, a, b);
q = g3[ b00 + bz1 ] ; u = at3(rx0,ry0,rz1);
q = g3[ b10 + bz1 ] ; v = at3(rx1,ry0,rz1);
a = lerp(t, u, v);
q = g3[ b01 + bz1 ] ; u = at3(rx0,ry1,rz1);
q = g3[ b11 + bz1 ] ; v = at3(rx1,ry1,rz1);
b = lerp(t, u, v);
d = lerp(sy, a, b);
return lerp(sz, c, d);
}
void Perlin::normalize2(float v[2])
{
float s;
s = (float)sqrt(v[0] * v[0] + v[1] * v[1]);
s = 1.0f/s;
v[0] = v[0] * s;
v[1] = v[1] * s;
}
void Perlin::normalize3(float v[3])
{
float s;
s = (float)sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
s = 1.0f/s;
v[0] = v[0] * s;
v[1] = v[1] * s;
v[2] = v[2] * s;
}
void Perlin::init(void)
{
int i, j, k;
for (i = 0 ; i < B ; i++)
{
p[i] = i;
g1[i] = (float)((rand() % (B + B)) - B) / B;
for (j = 0 ; j < 2 ; j++)
g2[i][j] = (float)((rand() % (B + B)) - B) / B;
normalize2(g2[i]);
for (j = 0 ; j < 3 ; j++)
g3[i][j] = (float)((rand() % (B + B)) - B) / B;
normalize3(g3[i]);
}
while (--i)
{
k = p[i];
p[i] = p[j = rand() % B];
p[j] = k;
}
for (i = 0 ; i < B + 2 ; i++)
{
p[B + i] = p[i];
g1[B + i] = g1[i];
for (j = 0 ; j < 2 ; j++)
g2[B + i][j] = g2[i][j];
for (j = 0 ; j < 3 ; j++)
g3[B + i][j] = g3[i][j];
}
}
float Perlin::perlin_noise_2D(float vec[2])
{
int terms = mOctaves;
float result = 0.0f;
float amp = mAmplitude;
vec[0]*=mFrequency;
vec[1]*=mFrequency;
for( int i=0; i<terms; i++ )
{
result += noise2(vec)*amp;
vec[0] *= 2.0f;
vec[1] *= 2.0f;
amp*=0.5f;
}
return result;
}
float Perlin::perlin_noise_3D(float vec[3])
{
int terms = mOctaves;
float result = 0.0f;
float amp = mAmplitude;
vec[0]*=mFrequency;
vec[1]*=mFrequency;
vec[2]*=mFrequency;
for( int i=0; i<terms; i++ )
{
result += noise3(vec)*amp;
vec[0] *= 2.0f;
vec[1] *= 2.0f;
vec[2] *= 2.0f;
amp*=0.5f;
}
return result;
}
Perlin::Perlin(int octaves,float freq,float amp,int seed)
{
mOctaves = octaves;
mFrequency = freq;
mAmplitude = amp;
mSeed = seed;
mStart = true;
}

View File

@ -1,64 +1,64 @@
// Code from http://www.flipcode.com/archives/Perlin_Noise_Class.shtml
// This is only in PolyVox for the purpose of the examples. It was not written by
// the PolyVox authors and cannot be assumed to be under the same license as PolyVox.
#ifndef PERLIN_H_
#define PERLIN_H_
#include <stdlib.h>
#define SAMPLE_SIZE 1024
class Perlin
{
public:
Perlin(int octaves,float freq,float amp,int seed);
float Get(float x,float y)
{
float vec[2];
vec[0] = x;
vec[1] = y;
return perlin_noise_2D(vec);
};
float Get3D(float x,float y,float z)
{
float vec[3];
vec[0] = x;
vec[1] = y;
vec[2] = z;
return perlin_noise_3D(vec);
};
private:
void init_perlin(int n,float p);
float perlin_noise_2D(float vec[2]);
float perlin_noise_3D(float vec[3]);
float noise1(float arg);
float noise2(float vec[2]);
float noise3(float vec[3]);
void normalize2(float v[2]);
void normalize3(float v[3]);
void init(void);
int mOctaves;
float mFrequency;
float mAmplitude;
int mSeed;
int p[SAMPLE_SIZE + SAMPLE_SIZE + 2];
float g3[SAMPLE_SIZE + SAMPLE_SIZE + 2][3];
float g2[SAMPLE_SIZE + SAMPLE_SIZE + 2][2];
float g1[SAMPLE_SIZE + SAMPLE_SIZE + 2];
bool mStart;
};
#endif
// Code from http://www.flipcode.com/archives/Perlin_Noise_Class.shtml
// This is only in PolyVox for the purpose of the examples. It was not written by
// the PolyVox authors and cannot be assumed to be under the same license as PolyVox.
#ifndef PERLIN_H_
#define PERLIN_H_
#include <stdlib.h>
#define SAMPLE_SIZE 1024
class Perlin
{
public:
Perlin(int octaves,float freq,float amp,int seed);
float Get(float x,float y)
{
float vec[2];
vec[0] = x;
vec[1] = y;
return perlin_noise_2D(vec);
};
float Get3D(float x,float y,float z)
{
float vec[3];
vec[0] = x;
vec[1] = y;
vec[2] = z;
return perlin_noise_3D(vec);
};
private:
void init_perlin(int n,float p);
float perlin_noise_2D(float vec[2]);
float perlin_noise_3D(float vec[3]);
float noise1(float arg);
float noise2(float vec[2]);
float noise3(float vec[3]);
void normalize2(float v[2]);
void normalize3(float v[3]);
void init(void);
int mOctaves;
float mFrequency;
float mAmplitude;
int mSeed;
int p[SAMPLE_SIZE + SAMPLE_SIZE + 2];
float g3[SAMPLE_SIZE + SAMPLE_SIZE + 2][3];
float g2[SAMPLE_SIZE + SAMPLE_SIZE + 2][2];
float g1[SAMPLE_SIZE + SAMPLE_SIZE + 2];
bool mStart;
};
#endif

View File

@ -1,201 +1,186 @@
/*******************************************************************************
Copyright (c) 2005-2009 David Williams
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*******************************************************************************/
#include "OpenGLWidget.h"
#include "Perlin.h"
#include "PolyVoxCore/MaterialDensityPair.h"
#include "PolyVoxCore/CubicSurfaceExtractorWithNormals.h"
#include "PolyVoxCore/MarchingCubesSurfaceExtractor.h"
#include "PolyVoxCore/Pager.h"
#include "PolyVoxCore/RLEBlockCompressor.h"
#include "PolyVoxCore/SurfaceMesh.h"
#include "PolyVoxCore/LargeVolume.h"
#include <QApplication>
//Use the PolyVox namespace
using namespace PolyVox;
void createSphereInVolume(LargeVolume<MaterialDensityPair44>& volData, Vector3DFloat v3dVolCenter, float fRadius)
{
//This vector hold the position of the center of the volume
//Vector3DFloat v3dVolCenter(volData.getWidth() / 2, volData.getHeight() / 2, volData.getDepth() / 2);
int iRadius = fRadius;
//This three-level for loop iterates over every voxel in the volume
for (int z = v3dVolCenter.getZ() - iRadius; z <= v3dVolCenter.getZ() + iRadius; z++)
{
for (int y = v3dVolCenter.getY() - iRadius; y <= v3dVolCenter.getY() + iRadius; y++)
{
for (int x = v3dVolCenter.getX() - iRadius; x <= v3dVolCenter.getX() + iRadius; x++)
{
//Store our current position as a vector...
Vector3DFloat v3dCurrentPos(x,y,z);
//And compute how far the current position is from the center of the volume
float fDistToCenter = (v3dCurrentPos - v3dVolCenter).length();
//If the current voxel is less than 'radius' units from the center then we make it solid.
if(fDistToCenter <= fRadius)
{
//Our new density value
uint8_t uDensity = MaterialDensityPair44::getMaxDensity();
//Get the old voxel
MaterialDensityPair44 voxel = volData.getVoxel(x,y,z);
//Modify the density
voxel.setDensity(uDensity);
//Wrte the voxel value into the volume
volData.setVoxelAt(x, y, z, voxel);
}
}
}
}
}
/**
* Generates data using Perlin noise.
*/
class PerlinNoisePager : public PolyVox::Pager<MaterialDensityPair44>
{
public:
/// Constructor
PerlinNoisePager()
:Pager<MaterialDensityPair44>()
{
}
/// Destructor
virtual ~PerlinNoisePager() {};
virtual void pageIn(const PolyVox::Region& region, CompressedBlock<MaterialDensityPair44>* pBlockData)
{
// FIXME - this isn't a great example... it's a shame we have to hard clode the block size and also create/destroy
// a compressor each time. These could at least be moved outside somewhere if we can't fix it in a better way...
UncompressedBlock<MaterialDensityPair44> block(256);
Perlin perlin(2,2,1,234);
for(int x = region.getLowerX(); x <= region.getUpperX(); x++)
{
for(int y = region.getLowerY(); y <= region.getUpperY(); y++)
{
float perlinVal = perlin.Get(x / static_cast<float>(255-1), y / static_cast<float>(255-1));
perlinVal += 1.0f;
perlinVal *= 0.5f;
perlinVal *= 255;
for(int z = region.getLowerZ(); z <= region.getUpperZ(); z++)
{
MaterialDensityPair44 voxel;
if(z < perlinVal)
{
const int xpos = 50;
const int zpos = 100;
if((x-xpos)*(x-xpos) + (z-zpos)*(z-zpos) < 200) {
// tunnel
voxel.setMaterial(0);
voxel.setDensity(MaterialDensityPair44::getMinDensity());
} else {
// solid
voxel.setMaterial(245);
voxel.setDensity(MaterialDensityPair44::getMaxDensity());
}
}
else
{
voxel.setMaterial(0);
voxel.setDensity(MaterialDensityPair44::getMinDensity());
}
// Voxel position within a block always start from zero. So if a block represents region (4, 8, 12) to (11, 19, 15)
// then the valid block voxels are from (0, 0, 0) to (7, 11, 3). Hence we subtract the lower corner position of the
// region from the volume space position in order to get the block space position.
block.setVoxelAt(x - region.getLowerX(), y - region.getLowerY(), z - region.getLowerZ(), voxel);
}
}
}
// Now compress the computed data into the provided block.
RLEBlockCompressor<MaterialDensityPair44>* compressor = new RLEBlockCompressor<MaterialDensityPair44>();
compressor->compress(&block, pBlockData);
delete compressor;
}
virtual void pageOut(const PolyVox::Region& region, CompressedBlock<MaterialDensityPair44>* /*pBlockData*/)
{
std::cout << "warning unloading region: " << region.getLowerCorner() << " -> " << region.getUpperCorner() << std::endl;
}
};
int main(int argc, char *argv[])
{
//Create and show the Qt OpenGL window
QApplication app(argc, argv);
OpenGLWidget openGLWidget(0);
openGLWidget.show();
RLEBlockCompressor<MaterialDensityPair44>* compressor = new RLEBlockCompressor<MaterialDensityPair44>();
PerlinNoisePager* pager = new PerlinNoisePager();
LargeVolume<MaterialDensityPair44> volData(PolyVox::Region::MaxRegion, compressor, pager, 256);
volData.setMaxNumberOfBlocksInMemory(4096);
volData.setMaxNumberOfUncompressedBlocks(64);
//volData.setMaxNumberOfUncompressedBlocks(4096);
//createSphereInVolume(volData, 30);
//createPerlinTerrain(volData);
//createPerlinVolumeSlow(volData);
std::cout << "Memory usage: " << (volData.calculateSizeInBytes()/1024.0/1024.0) << "MB" << std::endl;
std::cout << "Compression ratio: 1 to " << (1.0/(volData.calculateCompressionRatio())) << std::endl;
//volData.setBlockCacheSize(64);
PolyVox::Region reg(Vector3DInt32(-255,0,0), Vector3DInt32(255,255,255));
std::cout << "Prefetching region: " << reg.getLowerCorner() << " -> " << reg.getUpperCorner() << std::endl;
volData.prefetch(reg);
std::cout << "Memory usage: " << (volData.calculateSizeInBytes()/1024.0/1024.0) << "MB" << std::endl;
std::cout << "Compression ratio: 1 to " << (1.0/(volData.calculateCompressionRatio())) << std::endl;
PolyVox::Region reg2(Vector3DInt32(0,0,0), Vector3DInt32(255,255,255));
std::cout << "Flushing region: " << reg2.getLowerCorner() << " -> " << reg2.getUpperCorner() << std::endl;
volData.flush(reg2);
std::cout << "Memory usage: " << (volData.calculateSizeInBytes()/1024.0/1024.0) << "MB" << std::endl;
std::cout << "Compression ratio: 1 to " << (1.0/(volData.calculateCompressionRatio())) << std::endl;
std::cout << "Flushing entire volume" << std::endl;
volData.flushAll();
std::cout << "Memory usage: " << (volData.calculateSizeInBytes()/1024.0/1024.0) << "MB" << std::endl;
std::cout << "Compression ratio: 1 to " << (1.0/(volData.calculateCompressionRatio())) << std::endl;
//Extract the surface
SurfaceMesh<PositionMaterialNormal> mesh;
CubicSurfaceExtractorWithNormals< LargeVolume<MaterialDensityPair44> > surfaceExtractor(&volData, reg, &mesh);
//MarchingCubesSurfaceExtractor< LargeVolume<MaterialDensityPair44> > surfaceExtractor(&volData, reg, &mesh);
//CubicSurfaceExtractorWithNormals<MaterialDensityPair44> surfaceExtractor(&volData, reg, &mesh);
surfaceExtractor.execute();
std::cout << "#vertices: " << mesh.getNoOfVertices() << std::endl;
//Pass the surface to the OpenGL window
openGLWidget.setSurfaceMeshToRender(mesh);
//Run the message pump.
return app.exec();
}
/*******************************************************************************
Copyright (c) 2005-2009 David Williams
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*******************************************************************************/
#include "OpenGLWidget.h"
#include "Perlin.h"
#include "PolyVox/MaterialDensityPair.h"
#include "PolyVox/CubicSurfaceExtractor.h"
#include "PolyVox/MarchingCubesSurfaceExtractor.h"
#include "PolyVox/Mesh.h"
#include "PolyVox/PagedVolume.h"
#include <QApplication>
//Use the PolyVox namespace
using namespace PolyVox;
void createSphereInVolume(PagedVolume<MaterialDensityPair44>& volData, Vector3DFloat v3dVolCenter, float fRadius)
{
//This vector hold the position of the center of the volume
//Vector3DFloat v3dVolCenter(volData.getWidth() / 2, volData.getHeight() / 2, volData.getDepth() / 2);
int iRadius = fRadius;
//This three-level for loop iterates over every voxel in the volume
for (int z = v3dVolCenter.getZ() - iRadius; z <= v3dVolCenter.getZ() + iRadius; z++)
{
for (int y = v3dVolCenter.getY() - iRadius; y <= v3dVolCenter.getY() + iRadius; y++)
{
for (int x = v3dVolCenter.getX() - iRadius; x <= v3dVolCenter.getX() + iRadius; x++)
{
//Store our current position as a vector...
Vector3DFloat v3dCurrentPos(x,y,z);
//And compute how far the current position is from the center of the volume
float fDistToCenter = (v3dCurrentPos - v3dVolCenter).length();
//If the current voxel is less than 'radius' units from the center then we make it solid.
if(fDistToCenter <= fRadius)
{
//Our new density value
uint8_t uDensity = MaterialDensityPair44::getMaxDensity();
//Get the old voxel
MaterialDensityPair44 voxel = volData.getVoxel(x,y,z);
//Modify the density
voxel.setDensity(uDensity);
//Wrte the voxel value into the volume
volData.setVoxelAt(x, y, z, voxel);
}
}
}
}
}
/**
* Generates data using Perlin noise.
*/
class PerlinNoisePager : public PolyVox::PagedVolume<MaterialDensityPair44>::Pager
{
public:
/// Constructor
PerlinNoisePager()
:PagedVolume<MaterialDensityPair44>::Pager()
{
}
/// Destructor
virtual ~PerlinNoisePager() {};
virtual void pageIn(const PolyVox::Region& region, PagedVolume<MaterialDensityPair44>::Chunk* pChunk)
{
Perlin perlin(2,2,1,234);
for(int x = region.getLowerX(); x <= region.getUpperX(); x++)
{
for(int y = region.getLowerY(); y <= region.getUpperY(); y++)
{
float perlinVal = perlin.Get(x / static_cast<float>(255-1), y / static_cast<float>(255-1));
perlinVal += 1.0f;
perlinVal *= 0.5f;
perlinVal *= 255;
for(int z = region.getLowerZ(); z <= region.getUpperZ(); z++)
{
MaterialDensityPair44 voxel;
if(z < perlinVal)
{
const int xpos = 50;
const int zpos = 100;
if((x-xpos)*(x-xpos) + (z-zpos)*(z-zpos) < 200) {
// tunnel
voxel.setMaterial(0);
voxel.setDensity(MaterialDensityPair44::getMinDensity());
} else {
// solid
voxel.setMaterial(245);
voxel.setDensity(MaterialDensityPair44::getMaxDensity());
}
}
else
{
voxel.setMaterial(0);
voxel.setDensity(MaterialDensityPair44::getMinDensity());
}
// Voxel position within a chunk always start from zero. So if a chunk represents region (4, 8, 12) to (11, 19, 15)
// then the valid chunk voxels are from (0, 0, 0) to (7, 11, 3). Hence we subtract the lower corner position of the
// region from the volume space position in order to get the chunk space position.
pChunk->setVoxelAt(x - region.getLowerX(), y - region.getLowerY(), z - region.getLowerZ(), voxel);
}
}
}
}
virtual void pageOut(const PolyVox::Region& region, PagedVolume<MaterialDensityPair44>::Chunk* /*pChunk*/)
{
std::cout << "warning unloading region: " << region.getLowerCorner() << " -> " << region.getUpperCorner() << std::endl;
}
};
int main(int argc, char *argv[])
{
//Create and show the Qt OpenGL window
QApplication app(argc, argv);
OpenGLWidget openGLWidget(0);
openGLWidget.show();
PerlinNoisePager* pager = new PerlinNoisePager();
PagedVolume<MaterialDensityPair44> volData(PolyVox::Region::MaxRegion(), pager, 64);
volData.setMemoryUsageLimit(8 * 1024 * 1024); // 8Mb
//createSphereInVolume(volData, 30);
//createPerlinTerrain(volData);
//createPerlinVolumeSlow(volData);
std::cout << "Memory usage: " << (volData.calculateSizeInBytes()/1024.0/1024.0) << "MB" << std::endl;
//std::cout << "Compression ratio: 1 to " << (1.0/(volData.calculateCompressionRatio())) << std::endl;
PolyVox::Region reg(Vector3DInt32(-255,0,0), Vector3DInt32(255,255,255));
std::cout << "Prefetching region: " << reg.getLowerCorner() << " -> " << reg.getUpperCorner() << std::endl;
volData.prefetch(reg);
std::cout << "Memory usage: " << (volData.calculateSizeInBytes()/1024.0/1024.0) << "MB" << std::endl;
//std::cout << "Compression ratio: 1 to " << (1.0/(volData.calculateCompressionRatio())) << std::endl;
PolyVox::Region reg2(Vector3DInt32(0,0,0), Vector3DInt32(255,255,255));
std::cout << "Flushing region: " << reg2.getLowerCorner() << " -> " << reg2.getUpperCorner() << std::endl;
volData.flush(reg2);
std::cout << "Memory usage: " << (volData.calculateSizeInBytes()/1024.0/1024.0) << "MB" << std::endl;
//std::cout << "Compression ratio: 1 to " << (1.0/(volData.calculateCompressionRatio())) << std::endl;
std::cout << "Flushing entire volume" << std::endl;
volData.flushAll();
std::cout << "Memory usage: " << (volData.calculateSizeInBytes()/1024.0/1024.0) << "MB" << std::endl;
//std::cout << "Compression ratio: 1 to " << (1.0/(volData.calculateCompressionRatio())) << std::endl;
//Extract the surface
auto mesh = extractCubicMesh(&volData, reg2);
std::cout << "#vertices: " << mesh.getNoOfVertices() << std::endl;
auto decodedMesh = decodeMesh(mesh);
//Pass the surface to the OpenGL window
openGLWidget.addMesh(decodedMesh);
openGLWidget.setViewableRegion(reg2);
//Run the message pump.
return app.exec();
}

View File

@ -1,26 +1,24 @@
# Copyright (c) 2010-2013 Matt Williams
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.
#
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
#
# 1. The origin of this software must not be misrepresented; you must not
# claim that you wrote the original software. If you use this software
# in a product, an acknowledgment in the product documentation would be
# appreciated but is not required.
#
# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.
#
# 3. This notice may not be removed or altered from any source
# distribution.
PROJECT(PythonExample)
SOURCE_GROUP("Sources" FILES PythonExample.py)
configure_file(PythonExample.py PythonExample.py COPYONLY)
# Copyright (c) 2010-2013 Matt Williams
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.
#
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
#
# 1. The origin of this software must not be misrepresented; you must not
# claim that you wrote the original software. If you use this software
# in a product, an acknowledgment in the product documentation would be
# appreciated but is not required.
#
# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.
#
# 3. This notice may not be removed or altered from any source
# distribution.
PROJECT(PythonExample)
configure_file(PythonExample.py PythonExample.py COPYONLY)

View File

@ -1,71 +1,69 @@
# Copyright (c) 2010-2012 David Williams
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.
#
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
#
# 1. The origin of this software must not be misrepresented; you must not
# claim that you wrote the original software. If you use this software
# in a product, an acknowledgment in the product documentation would be
# appreciated but is not required.
#
# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.
#
# 3. This notice may not be removed or altered from any source
# distribution.
PROJECT(SmoothLODExample)
#Projects source files
SET(SRC_FILES
main.cpp
OpenGLWidget.cpp
)
#Projects headers files
SET(INC_FILES
OpenGLWidget.h
)
add_definitions(-DGLEW_STATIC)
#"Sources" and "Headers" are the group names in Visual Studio.
#They may have other uses too...
SOURCE_GROUP("Sources" FILES ${SRC_FILES})
SOURCE_GROUP("Headers" FILES ${INC_FILES})
FIND_PACKAGE(OpenGL REQUIRED)
#Tell CMake the paths for OpenGL and for PolyVox (which is just relative to our current location)
INCLUDE_DIRECTORIES(${OPENGL_INCLUDE_DIR} ${PolyVoxCore_BINARY_DIR}/include ${PolyVoxCore_SOURCE_DIR}/include ${GLEW_SOURCE_DIR})
LINK_DIRECTORIES(${PolyVoxCore_BINARY_DIR})
#Build
ADD_EXECUTABLE(SmoothLODExample ${SRC_FILES})
IF(MSVC)
SET_TARGET_PROPERTIES(SmoothLODExample PROPERTIES COMPILE_FLAGS "/W4 /wd4127") #All warnings
ENDIF(MSVC)
TARGET_LINK_LIBRARIES(SmoothLODExample glew Qt5::OpenGL ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY} PolyVoxCore)
SET_PROPERTY(TARGET SmoothLODExample PROPERTY FOLDER "Examples")
#Install - Only install the example in Windows
IF(WIN32)
INSTALL(TARGETS SmoothLODExample
RUNTIME DESTINATION Examples/OpenGL/bin
LIBRARY DESTINATION Examples/OpenGL/lib
ARCHIVE DESTINATION Examples/OpenGL/lib
COMPONENT example
)
#.dlls should be installed in shared builds.
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../release/PolyVoxCore.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Release)
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../release/PolyVoxUtil.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Release)
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../debug/PolyVoxCore.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Debug)
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../debug/PolyVoxUtil.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Debug)
ENDIF(WIN32)
# Copyright (c) 2010-2012 David Williams
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.
#
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
#
# 1. The origin of this software must not be misrepresented; you must not
# claim that you wrote the original software. If you use this software
# in a product, an acknowledgment in the product documentation would be
# appreciated but is not required.
#
# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.
#
# 3. This notice may not be removed or altered from any source
# distribution.
CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
PROJECT(SmoothLODExample)
#Projects source files
SET(SRC_FILES
main.cpp
../common/OpenGLWidget.cpp
)
#Projects headers files
SET(INC_FILES
OpenGLWidget.h
)
add_definitions(-DGLEW_STATIC)
FIND_PACKAGE(OpenGL REQUIRED)
#Tell CMake the paths for OpenGL and for PolyVox (which is just relative to our current location)
INCLUDE_DIRECTORIES(${OPENGL_INCLUDE_DIR} ${PolyVoxHeaders_SOURCE_DIR} ${GLEW_SOURCE_DIR})
#This will include the shader files inside the compiled binary
QT4_ADD_RESOURCES(COMMON_RESOURCES_RCC ../common/example.qrc)
# Put the resources in a seperate folder in Visual Studio
SOURCE_GROUP("Resource Files" FILES ../common/example.qrc ${COMMON_RESOURCES_RCC})
#Build
ADD_EXECUTABLE(SmoothLODExample ${SRC_FILES} ${COMMON_RESOURCES_RCC})
IF(MSVC)
SET_TARGET_PROPERTIES(SmoothLODExample PROPERTIES COMPILE_FLAGS "/W4 /wd4127") #All warnings
ENDIF(MSVC)
TARGET_LINK_LIBRARIES(SmoothLODExample glew ${QT_LIBRARIES} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY})
SET_PROPERTY(TARGET SmoothLODExample PROPERTY FOLDER "Examples")
configure_file(../common/example.vert example.vert COPYONLY)
configure_file(../common/example.frag example.frag COPYONLY)
#Install - Only install the example in Windows
IF(WIN32)
INSTALL(TARGETS SmoothLODExample
RUNTIME DESTINATION Examples/OpenGL/bin
LIBRARY DESTINATION Examples/OpenGL/lib
ARCHIVE DESTINATION Examples/OpenGL/lib
COMPONENT example
)
ENDIF(WIN32)

View File

@ -1,186 +0,0 @@
#include "OpenGLWidget.h"
#include <QMouseEvent>
using namespace PolyVox;
using namespace std;
OpenGLWidget::OpenGLWidget(QWidget *parent)
:QGLWidget(parent)
,m_xRotation(0)
,m_yRotation(0)
{
}
void OpenGLWidget::setSurfaceMeshToRender(const PolyVox::SurfaceMesh<PositionMaterialNormal>& surfaceMesh)
{
//Convienient access to the vertices and indices
const vector<uint32_t>& vecIndices = surfaceMesh.getIndices();
const vector<PositionMaterialNormal>& vecVertices = surfaceMesh.getVertices();
//Build an OpenGL index buffer
glGenBuffers(1, &indexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
const GLvoid* pIndices = static_cast<const GLvoid*>(&(vecIndices[0]));
glBufferData(GL_ELEMENT_ARRAY_BUFFER, vecIndices.size() * sizeof(uint32_t), pIndices, GL_STATIC_DRAW);
//Build an OpenGL vertex buffer
glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
const GLvoid* pVertices = static_cast<const GLvoid*>(&(vecVertices[0]));
glBufferData(GL_ARRAY_BUFFER, vecVertices.size() * sizeof(PositionMaterialNormal), pVertices, GL_STATIC_DRAW);
m_uBeginIndex = 0;
m_uEndIndex = vecIndices.size();
}
void OpenGLWidget::setSurfaceMeshToRenderLowLOD(const PolyVox::SurfaceMesh<PositionMaterialNormal>& surfaceMesh)
{
//Convienient access to the vertices and indices
const vector<uint32_t>& vecIndices = surfaceMesh.getIndices();
const vector<PositionMaterialNormal>& vecVertices = surfaceMesh.getVertices();
//Build an OpenGL index buffer
glGenBuffers(1, &indexBufferLow);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferLow);
const GLvoid* pIndices = static_cast<const GLvoid*>(&(vecIndices[0]));
glBufferData(GL_ELEMENT_ARRAY_BUFFER, vecIndices.size() * sizeof(uint32_t), pIndices, GL_STATIC_DRAW);
//Build an OpenGL vertex buffer
glGenBuffers(1, &vertexBufferLow);
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferLow);
const GLvoid* pVertices = static_cast<const GLvoid*>(&(vecVertices[0]));
glBufferData(GL_ARRAY_BUFFER, vecVertices.size() * sizeof(PositionMaterialNormal), pVertices, GL_STATIC_DRAW);
m_uBeginIndexLow = 0;
m_uEndIndexLow = vecIndices.size();
}
void OpenGLWidget::initializeGL()
{
//We need GLEW to access recent OpenGL functionality
std::cout << "Initialising GLEW...";
GLenum result = glewInit();
if (result == GLEW_OK)
{
std::cout << "success" << std::endl;
}
else
{
/* Problem: glewInit failed, something is seriously wrong. */
std::cout << "failed" << std::endl;
std::cout << "Initialising GLEW failed with the following error: " << glewGetErrorString(result) << std::endl;
exit(EXIT_FAILURE);
}
//Print out some information about the OpenGL implementation.
std::cout << "OpenGL Implementation Details:" << std::endl;
if(glGetString(GL_VENDOR))
std::cout << "\tGL_VENDOR: " << glGetString(GL_VENDOR) << std::endl;
if(glGetString(GL_RENDERER))
std::cout << "\tGL_RENDERER: " << glGetString(GL_RENDERER) << std::endl;
if(glGetString(GL_VERSION))
std::cout << "\tGL_VERSION: " << glGetString(GL_VERSION) << std::endl;
if(glGetString(GL_SHADING_LANGUAGE_VERSION))
std::cout << "\tGL_SHADING_LANGUAGE_VERSION: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;
//Check our version of OpenGL is recent enough.
//We need at least 1.5 for vertex buffer objects,
if (!GLEW_VERSION_1_5)
{
std::cout << "Error: You need OpenGL version 1.5 to run this example." << std::endl;
exit(EXIT_FAILURE);
}
//Set up the clear colour
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClearDepth(1.0f);
//Enable the depth buffer
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
//Anable smooth lighting
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glShadeModel(GL_SMOOTH);
//We'll be rendering with index/vertex arrays
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
}
void OpenGLWidget::resizeGL(int w, int h)
{
//Setup the viewport
glViewport(0, 0, w, h);
//Set up the projection matrix
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
float frustumSize = 32.0f; //Half the volume size
float aspect = static_cast<float>(width()) / static_cast<float>(height());
glOrtho(frustumSize*aspect, -frustumSize*aspect, frustumSize, -frustumSize, 1.0, 1000);
}
void OpenGLWidget::paintGL()
{
//Clear the screen
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//Set up the viewing transformation
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0f,0.0f,-100.0f); //Centre volume and move back
glRotatef(-m_xRotation, 0.0f, 1.0f, 0.0f);
glRotatef(-m_yRotation, 1.0f, 0.0f, 0.0f);
glTranslatef(-32.0f,-32.0f,-32.0f); //Centre volume and move back
//Bind the index buffer
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
//Bind the vertex buffer
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glVertexPointer(3, GL_FLOAT, sizeof(PositionMaterialNormal), 0);
glNormalPointer(GL_FLOAT, sizeof(PositionMaterialNormal), (GLvoid*)12);
glDrawRangeElements(GL_TRIANGLES, m_uBeginIndex, m_uEndIndex-1, m_uEndIndex - m_uBeginIndex, GL_UNSIGNED_INT, 0);
//Bind the index buffer
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferLow);
//Bind the vertex buffer
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferLow);
glVertexPointer(3, GL_FLOAT, sizeof(PositionMaterialNormal), 0);
glNormalPointer(GL_FLOAT, sizeof(PositionMaterialNormal), (GLvoid*)12);
glDrawRangeElements(GL_TRIANGLES, m_uBeginIndexLow, m_uEndIndexLow-1, m_uEndIndexLow - m_uBeginIndexLow, GL_UNSIGNED_INT, 0);
GLenum errCode = glGetError();
if(errCode != GL_NO_ERROR)
{
//What has replaced getErrorString() in the latest OpenGL?
std::cout << "OpenGL Error: " << errCode << std::endl;
}
}
void OpenGLWidget::mousePressEvent(QMouseEvent* event)
{
m_CurrentMousePos = event->pos();
m_LastFrameMousePos = m_CurrentMousePos;
update();
}
void OpenGLWidget::mouseMoveEvent(QMouseEvent* event)
{
m_CurrentMousePos = event->pos();
QPoint diff = m_CurrentMousePos - m_LastFrameMousePos;
m_xRotation += diff.x();
m_yRotation += diff.y();
m_LastFrameMousePos = m_CurrentMousePos;
update();
}

View File

@ -1,74 +0,0 @@
/*******************************************************************************
Copyright (c) 2005-2009 David Williams
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*******************************************************************************/
#ifndef __BasicExample_OpenGLWidget_H__
#define __BasicExample_OpenGLWidget_H__
#include "PolyVoxCore/SurfaceMesh.h"
#include "glew/glew.h"
#include <QGLWidget>
class OpenGLWidget : public QGLWidget
{
public:
//Constructor
OpenGLWidget(QWidget *parent);
//Mouse handling
void mouseMoveEvent(QMouseEvent* event);
void mousePressEvent(QMouseEvent* event);
//Convert a SrfaceMesh to OpenGL index/vertex buffers
void setSurfaceMeshToRender(const PolyVox::SurfaceMesh<PolyVox::PositionMaterialNormal>& surfaceMesh);
void setSurfaceMeshToRenderLowLOD(const PolyVox::SurfaceMesh<PolyVox::PositionMaterialNormal>& surfaceMesh);
protected:
//Qt OpenGL functions
void initializeGL();
void resizeGL(int w, int h);
void paintGL();
private:
//Index/vertex buffer data
GLuint m_uBeginIndex;
GLuint m_uEndIndex;
//GLuint noOfIndices;
GLuint indexBuffer;
GLuint vertexBuffer;
GLuint m_uBeginIndexLow;
GLuint m_uEndIndexLow;
//GLuint noOfIndicesLow;
GLuint indexBufferLow;
GLuint vertexBufferLow;
//Mouse data
QPoint m_LastFrameMousePos;
QPoint m_CurrentMousePos;
int m_xRotation;
int m_yRotation;
};
#endif //__BasicExample_OpenGLWidget_H__

View File

@ -1,110 +1,110 @@
/*******************************************************************************
Copyright (c) 2005-2009 David Williams
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*******************************************************************************/
#include "OpenGLWidget.h"
#include "PolyVoxCore/Density.h"
#include "PolyVoxCore/MarchingCubesSurfaceExtractor.h"
#include "PolyVoxCore/SurfaceMesh.h"
#include "PolyVoxCore/RawVolume.h"
#include "PolyVoxCore/SimpleVolume.h"
#include "PolyVoxCore/VolumeResampler.h"
#include <QApplication>
//Use the PolyVox namespace
using namespace PolyVox;
void createSphereInVolume(SimpleVolume<uint8_t>& volData, float fRadius)
{
//This vector hold the position of the center of the volume
Vector3DFloat v3dVolCenter(volData.getWidth() / 2, volData.getHeight() / 2, volData.getDepth() / 2);
//This three-level for loop iterates over every voxel in the volume
for (int z = 0; z < volData.getDepth(); z++)
{
for (int y = 0; y < volData.getHeight(); y++)
{
for (int x = 0; x < volData.getWidth(); x++)
{
//Store our current position as a vector...
Vector3DFloat v3dCurrentPos(x,y,z);
//And compute how far the current position is from the center of the volume
float fDistToCenter = (v3dCurrentPos - v3dVolCenter).length();
if(fDistToCenter <= fRadius)
{
//Our new density value
uint8_t uDensity = std::numeric_limits<uint8_t>::max();
//Wrte the voxel value into the volume
volData.setVoxelAt(x, y, z, uDensity);
}
//144 in the middle, (144 - 32) at the edges. Threshold of 128 is between these
//volData.setVoxelAt(x, y, z, 144 - fDistToCenter);
}
}
}
}
int main(int argc, char *argv[])
{
//Create and show the Qt OpenGL window
QApplication app(argc, argv);
OpenGLWidget openGLWidget(0);
openGLWidget.show();
//Create an empty volume and then place a sphere in it
SimpleVolume<uint8_t> volData(PolyVox::Region(Vector3DInt32(0,0,0), Vector3DInt32(63, 63, 63)));
createSphereInVolume(volData, 28);
//Smooth the data - should reimplement this using LowPassFilter
//smoothRegion<SimpleVolume, Density8>(volData, volData.getEnclosingRegion());
//smoothRegion<SimpleVolume, Density8>(volData, volData.getEnclosingRegion());
//smoothRegion<SimpleVolume, Density8>(volData, volData.getEnclosingRegion());
RawVolume<uint8_t> volDataLowLOD(PolyVox::Region(Vector3DInt32(0,0,0), Vector3DInt32(15, 31, 31)));
VolumeResampler< SimpleVolume<uint8_t>, RawVolume<uint8_t> > volumeResampler(&volData, PolyVox::Region(Vector3DInt32(0,0,0), Vector3DInt32(31, 63, 63)), &volDataLowLOD, volDataLowLOD.getEnclosingRegion());
volumeResampler.execute();
//Extract the surface
SurfaceMesh<PositionMaterialNormal> meshLowLOD;
MarchingCubesSurfaceExtractor< RawVolume<uint8_t> > surfaceExtractor(&volDataLowLOD, volDataLowLOD.getEnclosingRegion(), &meshLowLOD);
surfaceExtractor.execute();
meshLowLOD.scaleVertices(/*2.0f*/63.0f / 31.0f);
//Extract the surface
SurfaceMesh<PositionMaterialNormal> meshHighLOD;
MarchingCubesSurfaceExtractor< SimpleVolume<uint8_t> > surfaceExtractorHigh(&volData, PolyVox::Region(Vector3DInt32(30,0,0), Vector3DInt32(63, 63, 63)), &meshHighLOD);
surfaceExtractorHigh.execute();
meshHighLOD.translateVertices(Vector3DFloat(30, 0, 0));
//Pass the surface to the OpenGL window
openGLWidget.setSurfaceMeshToRender(meshHighLOD);
openGLWidget.setSurfaceMeshToRenderLowLOD(meshLowLOD);
//Run the message pump.
return app.exec();
}
/*******************************************************************************
Copyright (c) 2005-2009 David Williams
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*******************************************************************************/
#include "OpenGLWidget.h"
#include "PolyVox/Density.h"
#include "PolyVox/MarchingCubesSurfaceExtractor.h"
#include "PolyVox/Mesh.h"
#include "PolyVox/RawVolume.h"
#include "PolyVox/PagedVolume.h"
#include "PolyVox/VolumeResampler.h"
#include <QApplication>
//Use the PolyVox namespace
using namespace PolyVox;
void createSphereInVolume(PagedVolume<uint8_t>& volData, float fRadius)
{
//This vector hold the position of the center of the volume
Vector3DFloat v3dVolCenter(volData.getWidth() / 2, volData.getHeight() / 2, volData.getDepth() / 2);
//This three-level for loop iterates over every voxel in the volume
for (int z = 0; z < volData.getDepth(); z++)
{
for (int y = 0; y < volData.getHeight(); y++)
{
for (int x = 0; x < volData.getWidth(); x++)
{
//Store our current position as a vector...
Vector3DFloat v3dCurrentPos(x,y,z);
//And compute how far the current position is from the center of the volume
float fDistToCenter = (v3dCurrentPos - v3dVolCenter).length();
if(fDistToCenter <= fRadius)
{
//Our new density value
uint8_t uDensity = std::numeric_limits<uint8_t>::max();
//Wrte the voxel value into the volume
volData.setVoxelAt(x, y, z, uDensity);
}
//144 in the middle, (144 - 32) at the edges. Threshold of 128 is between these
//volData.setVoxelAt(x, y, z, 144 - fDistToCenter);
}
}
}
}
int main(int argc, char *argv[])
{
//Create and show the Qt OpenGL window
QApplication app(argc, argv);
OpenGLWidget openGLWidget(0);
openGLWidget.show();
//Create an empty volume and then place a sphere in it
PagedVolume<uint8_t> volData(PolyVox::Region(Vector3DInt32(0, 0, 0), Vector3DInt32(63, 63, 63)));
createSphereInVolume(volData, 28);
//Smooth the data - should reimplement this using LowPassFilter
//smoothRegion<PagedVolume, Density8>(volData, volData.getEnclosingRegion());
//smoothRegion<PagedVolume, Density8>(volData, volData.getEnclosingRegion());
//smoothRegion<PagedVolume, Density8>(volData, volData.getEnclosingRegion());
RawVolume<uint8_t> volDataLowLOD(PolyVox::Region(Vector3DInt32(0,0,0), Vector3DInt32(15, 31, 31)));
VolumeResampler< PagedVolume<uint8_t>, RawVolume<uint8_t> > volumeResampler(&volData, PolyVox::Region(Vector3DInt32(0, 0, 0), Vector3DInt32(31, 63, 63)), &volDataLowLOD, volDataLowLOD.getEnclosingRegion());
volumeResampler.execute();
//Extract the surface
auto meshLowLOD = extractMarchingCubesMesh(&volDataLowLOD, volDataLowLOD.getEnclosingRegion());
// The returned mesh needs to be decoded to be appropriate for GPU rendering.
auto decodedMeshLowLOD = decodeMesh(meshLowLOD);
//Extract the surface
auto meshHighLOD = extractMarchingCubesMesh(&volData, PolyVox::Region(Vector3DInt32(30, 0, 0), Vector3DInt32(63, 63, 63)));
// The returned mesh needs to be decoded to be appropriate for GPU rendering.
auto decodedMeshHighLOD = decodeMesh(meshHighLOD);
//Pass the surface to the OpenGL window
openGLWidget.addMesh(decodedMeshHighLOD, Vector3DInt32(30, 0, 0));
openGLWidget.addMesh(decodedMeshLowLOD, Vector3DInt32(0, 0, 0), 63.0f / 31.0f);
openGLWidget.setViewableRegion(volData.getEnclosingRegion());
//Run the message pump.
return app.exec();
}

View File

@ -0,0 +1,196 @@
#include "OpenGLWidget.h"
#include <QMouseEvent>
#include <QMatrix4x4>
#include <QCoreApplication>
//#include <QtMath>
using namespace PolyVox;
using namespace std;
////////////////////////////////////////////////////////////////////////////////
// Public functions
////////////////////////////////////////////////////////////////////////////////
OpenGLWidget::OpenGLWidget(QWidget *parent)
:QGLWidget(parent)
,m_viewableRegion(PolyVox::Region(0, 0, 0, 255, 255, 255))
,m_xRotation(0)
,m_yRotation(0)
{
}
void OpenGLWidget::setShader(QSharedPointer<QGLShaderProgram> shader)
{
mShader = shader;
}
void OpenGLWidget::setViewableRegion(PolyVox::Region viewableRegion)
{
m_viewableRegion = viewableRegion;
// The user has specifed a new viewable region
// so we need to regenerate our camera matrix.
setupWorldToCameraMatrix();
}
void OpenGLWidget::mousePressEvent(QMouseEvent* event)
{
// Initialise these variables which will be used when the mouse actually moves.
m_CurrentMousePos = event->pos();
m_LastFrameMousePos = m_CurrentMousePos;
}
void OpenGLWidget::mouseMoveEvent(QMouseEvent* event)
{
// Update the x and y rotations based on the mouse movement.
m_CurrentMousePos = event->pos();
QPoint diff = m_CurrentMousePos - m_LastFrameMousePos;
m_xRotation += diff.x();
m_yRotation += diff.y();
m_LastFrameMousePos = m_CurrentMousePos;
// The camera rotation has changed so we need to regenerate the matrix.
setupWorldToCameraMatrix();
// Re-render.
update();
}
////////////////////////////////////////////////////////////////////////////////
// Protected functions
////////////////////////////////////////////////////////////////////////////////
void OpenGLWidget::initializeGL()
{
GLenum err = glewInit();
if (GLEW_OK != err)
{
/* Problem: glewInit failed, something is seriously wrong. */
std::cout << "GLEW Error: " << glewGetErrorString(err) << std::endl;
}
//Print out some information about the OpenGL implementation.
std::cout << "OpenGL Implementation Details:" << std::endl;
if(glGetString(GL_VENDOR))
std::cout << "\tGL_VENDOR: " << glGetString(GL_VENDOR) << std::endl;
if(glGetString(GL_RENDERER))
std::cout << "\tGL_RENDERER: " << glGetString(GL_RENDERER) << std::endl;
if(glGetString(GL_VERSION))
std::cout << "\tGL_VERSION: " << glGetString(GL_VERSION) << std::endl;
if(glGetString(GL_SHADING_LANGUAGE_VERSION))
std::cout << "\tGL_SHADING_LANGUAGE_VERSION: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;
//Set up the clear colour
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClearDepth(1.0f);
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glDepthFunc(GL_LEQUAL);
glDepthRange(0.0, 1.0);
mShader = QSharedPointer<QGLShaderProgram>(new QGLShaderProgram);
// This is basically a simple fallback vertex shader which does the most basic rendering possible.
// PolyVox examples are able to provide their own shaders to demonstrate certain effects if desired.
if (!mShader->addShaderFromSourceFile(QGLShader::Vertex, ":/example.vert"))
{
std::cerr << mShader->log().toStdString() << std::endl;
exit(EXIT_FAILURE);
}
// This is basically a simple fallback fragment shader which does the most basic rendering possible.
// PolyVox examples are able to provide their own shaders to demonstrate certain effects if desired.
if (!mShader->addShaderFromSourceFile(QGLShader::Fragment, ":/example.frag"))
{
std::cerr << mShader->log().toStdString() << std::endl;
exit(EXIT_FAILURE);
}
// Bind the position semantic - this is defined in the vertex shader above.
mShader->bindAttributeLocation("position", 0);
// Bind the other semantics. Note that these don't actually exist in our example shader above! However, other
// example shaders may choose to provide them and having the binding code here does not seem to cause any problems.
mShader->bindAttributeLocation("normal", 1);
mShader->bindAttributeLocation("material", 2);
if (!mShader->link())
{
std::cerr << mShader->log().toStdString() << std::endl;
exit(EXIT_FAILURE);
}
// Initial setup of camera.
setupWorldToCameraMatrix();
}
void OpenGLWidget::resizeGL(int w, int h)
{
//Setup the viewport
glViewport(0, 0, w, h);
auto aspectRatio = w / (float)h;
float zNear = 1.0;
float zFar = 1000.0;
cameraToClipMatrix.setToIdentity();
cameraToClipMatrix.frustum(-aspectRatio, aspectRatio, -1, 1, zNear, zFar);
}
void OpenGLWidget::paintGL()
{
//Clear the screen
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Our example framework only uses a single shader for the scene (for all meshes).
mShader->bind();
// These two matrices are constant for all meshes.
mShader->setUniformValue("worldToCameraMatrix", worldToCameraMatrix);
mShader->setUniformValue("cameraToClipMatrix", cameraToClipMatrix);
// Iterate over each mesh which the user added to our list, and render it.
for (OpenGLMeshData meshData : mMeshData)
{
//Set up the model matrrix based on provided translation and scale.
QMatrix4x4 modelToWorldMatrix;
modelToWorldMatrix.translate(meshData.translation);
modelToWorldMatrix.scale(meshData.scale);
mShader->setUniformValue("modelToWorldMatrix", modelToWorldMatrix);
// Bind the vertex array for the current mesh
glBindVertexArray(meshData.vertexArrayObject);
// Draw the mesh
glDrawElements(GL_TRIANGLES, meshData.noOfIndices, meshData.indexType, 0);
// Unbind the vertex array.
glBindVertexArray(0);
}
// We're done with the shader for this frame.
mShader->release();
// Check for errors.
GLenum errCode = glGetError();
if(errCode != GL_NO_ERROR)
{
std::cerr << "OpenGL Error: " << errCode << std::endl;
}
}
////////////////////////////////////////////////////////////////////////////////
// Private functions
////////////////////////////////////////////////////////////////////////////////
void OpenGLWidget::setupWorldToCameraMatrix()
{
QVector3D lowerCorner(m_viewableRegion.getLowerX(), m_viewableRegion.getLowerY(), m_viewableRegion.getLowerZ());
QVector3D upperCorner(m_viewableRegion.getUpperX(), m_viewableRegion.getUpperY(), m_viewableRegion.getUpperZ());
QVector3D centerPoint = (lowerCorner + upperCorner) * 0.5;
float fDiagonalLength = (upperCorner - lowerCorner).length();
worldToCameraMatrix.setToIdentity();
worldToCameraMatrix.translate(0, 0, -fDiagonalLength / 2.0f); //Move the camera back by the required amount
worldToCameraMatrix.rotate(m_xRotation, 0, 1, 0); //rotate around y-axis
worldToCameraMatrix.rotate(m_yRotation, 1, 0, 0); //rotate around x-axis
worldToCameraMatrix.translate(-centerPoint); //centre the model on the origin
}

View File

@ -0,0 +1,160 @@
/*******************************************************************************
Copyright (c) 2005-2009 David Williams
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*******************************************************************************/
#ifndef __BasicExample_OpenGLWidget_H__
#define __BasicExample_OpenGLWidget_H__
#include "PolyVox/Mesh.h"
#include "glew/glew.h"
#include <QGLWidget>
#include <QGLShaderProgram>
// This structure holds all the data required
// to render one of our meshes through OpenGL.
struct OpenGLMeshData
{
GLuint noOfIndices;
GLenum indexType;
GLuint indexBuffer;
GLuint vertexBuffer;
GLuint vertexArrayObject;
QVector3D translation;
float scale;
};
// Our OpenGLWidget is used by all the examples to render the extracted meshes. It is
// fairly specific to our needs (you probably won't want to use it in your own project)
// but should provide a useful illustration of how PolyVox meshes can be rendered.
class OpenGLWidget : public QGLWidget
{
public:
// Constructor
OpenGLWidget(QWidget *parent);
// Convert a PolyVox mesh to OpenGL index/vertex buffers. Inlined because it's templatised.
template <typename MeshType>
void addMesh(const MeshType& surfaceMesh, const PolyVox::Vector3DInt32& translation = PolyVox::Vector3DInt32(0, 0, 0), float scale = 1.0f)
{
// Convienient access to the vertices and indices
const auto& vecIndices = surfaceMesh.getIndices();
const auto& vecVertices = surfaceMesh.getVertices();
// This struct holds the OpenGL properties (buffer handles, etc) which will be used
// to render our mesh. We copy the data from the PolyVox mesh into this structure.
OpenGLMeshData meshData;
// Create the VAO for the mesh
glGenVertexArrays(1, &(meshData.vertexArrayObject));
glBindVertexArray(meshData.vertexArrayObject);
// The GL_ARRAY_BUFFER will contain the list of vertex positions
glGenBuffers(1, &(meshData.vertexBuffer));
glBindBuffer(GL_ARRAY_BUFFER, meshData.vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, vecVertices.size() * sizeof(typename MeshType::VertexType), vecVertices.data(), GL_STATIC_DRAW);
// and GL_ELEMENT_ARRAY_BUFFER will contain the indices
glGenBuffers(1, &(meshData.indexBuffer));
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, meshData.indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, vecIndices.size() * sizeof(typename MeshType::IndexType), vecIndices.data(), GL_STATIC_DRAW);
// Every surface extractor outputs valid positions for the vertices, so tell OpenGL how these are laid out
glEnableVertexAttribArray(0); // Attrib '0' is the vertex positions
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(typename MeshType::VertexType), (GLvoid*)(offsetof(typename MeshType::VertexType, position))); //take the first 3 floats from every sizeof(decltype(vecVertices)::value_type)
// Some surface extractors also generate normals, so tell OpenGL how these are laid out. If a surface extractor
// does not generate normals then nonsense values are written into the buffer here and sghould be ignored by the
// shader. This is mostly just to simplify this example code - in a real application you will know whether your
// chosen surface extractor generates normals and can skip uploading them if not.
glEnableVertexAttribArray(1); // Attrib '1' is the vertex normals.
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(typename MeshType::VertexType), (GLvoid*)(offsetof(typename MeshType::VertexType, normal)));
// Finally a surface extractor will probably output additional data. This is highly application dependant. For this example code
// we're just uploading it as a set of bytes which we can read individually, but real code will want to do something specialised here.
glEnableVertexAttribArray(2); //We're talking about shader attribute '2'
GLint size = (std::min)(sizeof(typename MeshType::VertexType::DataType), size_t(4)); // Can't upload more that 4 components (vec4 is GLSL's biggest type)
glVertexAttribIPointer(2, size, GL_UNSIGNED_BYTE, sizeof(typename MeshType::VertexType), (GLvoid*)(offsetof(typename MeshType::VertexType, data)));
// We're done uploading and can now unbind.
glBindVertexArray(0);
// A few additional properties can be copied across for use during rendering.
meshData.noOfIndices = vecIndices.size();
meshData.translation = QVector3D(translation.getX(), translation.getY(), translation.getZ());
meshData.scale = scale;
// Set 16 or 32-bit index buffer size.
meshData.indexType = sizeof(typename MeshType::IndexType) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
// Now add the mesh to the list of meshes to render.
addMeshData(meshData);
}
void addMeshData(OpenGLMeshData meshData)
{
mMeshData.push_back(meshData);
}
// For our purposes we use a single shader for the whole volume, and
// this example framework is only meant to show a single volume at a time
void setShader(QSharedPointer<QGLShaderProgram> shader);
// The viewable region can be adjusted so that this example framework can be used for different volume sizes.
void setViewableRegion(PolyVox::Region viewableRegion);
// Mouse handling
void mouseMoveEvent(QMouseEvent* event);
void mousePressEvent(QMouseEvent* event);
protected:
// Qt OpenGL functions
void initializeGL();
void resizeGL(int w, int h);
void paintGL();
private:
void setupWorldToCameraMatrix();
// Index/vertex buffer data
std::vector<OpenGLMeshData> mMeshData;
QSharedPointer<QGLShaderProgram> mShader;
// Matrices
QMatrix4x4 worldToCameraMatrix;
QMatrix4x4 cameraToClipMatrix;
// Mouse data
QPoint m_LastFrameMousePos;
QPoint m_CurrentMousePos;
// Camera setup
PolyVox::Region m_viewableRegion;
int m_xRotation;
int m_yRotation;
};
#endif //__BasicExample_OpenGLWidget_H__

View File

@ -0,0 +1,19 @@
#version 130
// Passed in from the vertex shader
in vec4 worldPosition;
in vec4 worldNormal;
// the color that gets written to the display
out vec4 outputColor;
void main()
{
// Again, for the purposes of these examples we cannot be sure that per-vertex normals are provided. A sensible fallback
// is to use this little trick to compute per-fragment flat-shaded normals from the world positions using derivative operations.
vec3 normal = normalize(cross(dFdy(worldPosition.xyz), dFdx(worldPosition.xyz)));
// We are just using the normal as the output color, and making it lighter so it looks a bit nicer.
// Obviously a real shader would also do texuring, lighting, or whatever is required for the application.
outputColor = vec4(abs(normal) * 0.5 + vec3(0.5, 0.5, 0.5), 1.0);
}

View File

@ -0,0 +1,6 @@
<!DOCTYPE RCC><RCC version="1.0">
<qresource>
<file>example.vert</file>
<file>example.frag</file>
</qresource>
</RCC>

View File

@ -0,0 +1,20 @@
#version 140
in vec4 position; // This will be the position of the vertex in model-space
// The usual matrices are provided
uniform mat4 cameraToClipMatrix;
uniform mat4 worldToCameraMatrix;
uniform mat4 modelToWorldMatrix;
// This will be used by the fragment shader to calculate flat-shaded normals. This is an unconventional approach
// but we use it in this example framework because not all surface extractor generate surface normals.
out vec4 worldPosition;
void main()
{
// Standard sequence of OpenGL transformations.
worldPosition = modelToWorldMatrix * position;
vec4 cameraPosition = worldToCameraMatrix * worldPosition;
gl_Position = cameraToClipMatrix * cameraPosition;
}

View File

@ -1,73 +1,73 @@
The OpenGL Extension Wrangler Library
Copyright (C) 2002-2007, Milan Ikits <milan ikits[]ieee org>
Copyright (C) 2002-2007, Marcelo E. Magallon <mmagallo[]debian org>
Copyright (C) 2002, Lev Povalahev
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* The name of the author may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
Mesa 3-D graphics library
Version: 7.0
Copyright (C) 1999-2007 Brian Paul 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 and this permission notice 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
BRIAN PAUL 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.
Copyright (c) 2007 The Khronos Group Inc.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and/or associated documentation files (the
"Materials"), to deal in the Materials without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Materials, and to
permit persons to whom the Materials are furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Materials.
THE MATERIALS ARE 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 THE AUTHORS OR COPYRIGHT HOLDERS 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
MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
The OpenGL Extension Wrangler Library
Copyright (C) 2002-2007, Milan Ikits <milan ikits[]ieee org>
Copyright (C) 2002-2007, Marcelo E. Magallon <mmagallo[]debian org>
Copyright (C) 2002, Lev Povalahev
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* The name of the author may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
Mesa 3-D graphics library
Version: 7.0
Copyright (C) 1999-2007 Brian Paul 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 and this permission notice 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
BRIAN PAUL 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.
Copyright (c) 2007 The Khronos Group Inc.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and/or associated documentation files (the
"Materials"), to deal in the Materials without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Materials, and to
permit persons to whom the Materials are furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Materials.
THE MATERIALS ARE 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 THE AUTHORS OR COPYRIGHT HOLDERS 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
MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff