#ifndef OpenGLModelWidget_H
#define OpenGLModelWidget_H
#include <QOpenGLWidget>
#include <QOpenGlFunctions_3_3_Core>
#include <QMatrix4x4>
#include <QVector2D>
#include <QVector3D>
#include <QMouseEvent>
#include <array>
#include "glm/glm.hpp"
#include "glm/ext.hpp"
struct Vertex {
glm::vec3 position;
glm::vec3 normal;
};
class COpenGLModelWidget : public QOpenGLWidget, QOpenGLFunctions_3_3_Core
{
Q_OBJECT
public:
COpenGLModelWidget(QWidget*parent = nullptr);
virtual ~COpenGLModelWidget();
void LoadOBJModel(const std::string& strModelFile);
void SetShaderFilePath(const std::string& strVertFilePath, const std::string& strfragFilePath);
protected:
void initializeGL();
void paintGL();
void resizeGL(int width, int height);
void mouseMoveEvent(QMouseEvent* event);
void mousePressEvent(QMouseEvent* event);
void wheelEvent(QWheelEvent* event);
void mouseReleaseEvent(QMouseEvent* event);
void keyPressEvent(QKeyEvent* event);
void keyReleaseEvent(QKeyEvent* event);
private:
void AutoNormal();
std::string GetFileConTent(const std::string& strFilePath) const;
glm::vec3 ComputeNormalBiased(glm::vec3 const& a, glm::vec3 const& b,
glm::vec3 const& c);
glm::mat4x4 GetViewMatrix() const;
glm::mat4x4 GetProjectionMatrix() const;
void NormalizeAngle(int &nAngle);
void Orbit(glm::vec2 delta, bool isDrift);
void Zoom(float delta, bool isHitchcock);
void Pan(glm::vec2 delta);
private:
std::vector<Vertex> m_vecVertices;
std::vector<glm::uvec3> m_vecFaces;
unsigned int m_unVAO;
unsigned int m_unVBO;
unsigned int m_unEBO;
unsigned int m_unShaderProgram;
std::string m_strFragFilePath;
std::string m_strVertFilePath;
glm::vec2 lastpos;
bool moving = false;
glm::vec3 eye = {
0, 0, 5 };
glm::vec3 lookat = {
0, 0, 0 };
glm::vec3 up_vector = {
0, 1, 0 };
glm::vec3 keep_up_axis = {
0, 1, 0 };
float focal_len = 40.0f;
float film_height = 24.0f;
float film_width = 32.0f;
float zoom_speed = 0.2f;
float orbit_speed = 1.0f;
float drift_speed = 1.0f;
float pan_speed = 2.0f;
int zoom_axis = 1;
glm::vec2 mousePos;
};
#endif
#include "../Include/OpenGLModelWidget.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <QMatrix3x3>
COpenGLModelWidget::COpenGLModelWidget(QWidget* parent)
: QOpenGLWidget(parent)
{
}
COpenGLModelWidget::~COpenGLModelWidget()
{
makeCurrent();
glDeleteBuffers(1, &m_unVBO);
glDeleteVertexArrays(1, &m_unVAO);
glDeleteProgram(m_unShaderProgram);
doneCurrent();
}
void COpenGLModelWidget::LoadOBJModel(const std::string& strModelFile)
{
std::ifstream file(strModelFile);
if (!file.is_open()) {
std::cerr << "Failed to open file: " << strModelFile << std::endl;
return;
}
std::string line;
while (std::getline(file, line))
{
if (line.substr(0, 2) == "v ")
{
std::istringstream s(line.substr(2));
glm::vec3 vertex;
s >> vertex.x >> vertex.y >> vertex.z;
m_ve