From 131b7cac5efb171dcb6e8d18af9665285f955fed Mon Sep 17 00:00:00 2001 From: Muaz Ahmad Date: Wed, 3 May 2023 15:57:59 +0500 Subject: [PATCH] Finished rendering code --- obj.cpp | 5 +++-- opglwidget.cpp | 26 ++++++++++++++++++++++---- opglwidget.h | 2 ++ 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/obj.cpp b/obj.cpp index e449a7d..9a4a350 100644 --- a/obj.cpp +++ b/obj.cpp @@ -4,6 +4,7 @@ #include #include #include +#include void ObjectLoader::load_mtl(string filename) { string tmp; @@ -76,9 +77,9 @@ void ObjectLoader::load_obj(string filename) { regex_search(tmp, match, re); for (int i = 1; i < 7; i++) { if (i % 2 == 0) { - faces.back().normals.push_back(&(normals[stoi(match.str(i))])); + faces.back().normals.push_back(&(normals[stoi(match.str(i)) - 1])); } else { - faces.back().vertices.push_back(&(vertices[stoi(match.str(i))])); + faces.back().vertices.push_back(&(vertices[stoi(match.str(i)) - 1])); }; }; }; diff --git a/opglwidget.cpp b/opglwidget.cpp index f62c61f..cf0d9cd 100644 --- a/opglwidget.cpp +++ b/opglwidget.cpp @@ -2,7 +2,7 @@ #include #include #include -#include "obj.h" +#include void OPGLWidget::initializeGL() { glClearDepth(1.0f); @@ -22,7 +22,6 @@ void OPGLWidget::initializeGL() { glLightfv(GL_LIGHT0, GL_POSITION, light_position); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); - ObjectLoader obj; obj.load_mtl("untitled.mtl"); obj.load_obj("untitled.obj"); } @@ -30,7 +29,26 @@ void OPGLWidget::initializeGL() { void OPGLWidget::paintGL() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); - reorient(); + //reorient(); + glTranslatef(0.0f, 0.0f, -10.0f); + glPolygonMode(GL_FRONT, GL_FILL); + glBegin(GL_TRIANGLES); + for (int i = 0; i < obj.faces.size(); i++) { + Material* mtl_ptr = obj.faces[i].mtl; + if (mtl_idx != mtl_ptr->idx) { + glMaterialfv(GL_FRONT, GL_AMBIENT, mtl_ptr -> ambient); + glMaterialfv(GL_FRONT, GL_DIFFUSE, mtl_ptr -> diffuse); + glMaterialfv(GL_FRONT, GL_SPECULAR, mtl_ptr -> specular); + glMaterialf(GL_FRONT, GL_SHININESS, {128.0f}); + mtl_idx =mtl_ptr->idx; + }; + for (int j = 0; j < 3; j++) { + glVertex3fv(obj.faces[i].vertices[j] -> pos); + glNormal3fv(obj.faces[i].normals[j] -> dir); + }; + }; + glEnd(); + glFlush(); } void OPGLWidget::reorient() { @@ -54,6 +72,6 @@ void OPGLWidget::resizeGL(int w, int h) { float aspect = w / float(h); float top = 0.2f * tan(M_PI / 8); float right = 0.2f * tan(M_PI / 8) * aspect; - glFrustum(-right , right, -top, top, 0.1f, 100.0f); + glFrustum(-right, right, -top, top, 0.1f, 100.0f); glMatrixMode(GL_MODELVIEW); } diff --git a/opglwidget.h b/opglwidget.h index 2c56299..78f4f6e 100644 --- a/opglwidget.h +++ b/opglwidget.h @@ -1,4 +1,5 @@ #include +#include "obj.h" class OPGLWidget : public QOpenGLWidget { @@ -12,4 +13,5 @@ protected: int mtl_idx = -1; float loc[3] = {-10, 0, -10}; + ObjectLoader obj; };