1前面我们已经熟悉了opengl自定义顶点生成一个立方体,并且我们实现了立方体的旋转,光照等功能。下面我们来用opengl来加载一个obj文件。准备我们首先准备一个简单的obj文件(head.obj)。资源在本页下载

2 在obj文件里面,我们关注下 v 字段和f字段

 v 字段就是顶点  f字段代表了面,意思是每个面的顶点编号。 结构如下

v -0.99179999 -2.98999995 4.05410025  表示顶点值

f 12791 127 126   表示这个面的三个点在 v 里面的index值是12791 也是就是v[12791]的值的顶点是这个面的顶点值。

3 下面我们来解析obj文件

bool load(QString fileName, QVector<float>& vPoints)
{if (fileName.mid(fileName.lastIndexOf('.')) != ".obj" && fileName.mid(fileName.lastIndexOf('.')) != ".OBJ"){qDebug() << "file is not a obj file.";return false;}QFile objFile(fileName);if (!objFile.open(QIODevice::ReadOnly)){qDebug() << "open" << fileName << "failed";return false;}else{qDebug() << "open" << fileName << "success!";}QVector<float> vertextPoints, texturePoints, normalPoints;QVector<Face> facesIndexs;while (!objFile.atEnd()){QByteArray lineData = objFile.readLine();QList<QByteArray> strValues = lineData.trimmed().split(' ');QString dataType = strValues.takeFirst();for(int i=0;i<strValues.size();i++){double nData = strValues.at(i).toDouble();QString strTemp = QString::number(nData,'f',4);if (dataType == "v"){vertextPoints.append(strTemp.toFloat());}else if (dataType == "vt"){texturePoints.append(strValues.at(i).toFloat());}else if (dataType == "vn"){normalPoints.append(strValues.at(i).toFloat());}else if (dataType == "f"){Face ondInfo;if(strValues.at(i).contains("/")){QList<QByteArray> strTemp = strValues.at(i).split('/');if(strTemp.size()==2){ondInfo.vertices  =  strTemp.at(0).toInt();ondInfo.texCoords =  strTemp.at(1).toInt();}else if(strTemp.size()==3){ondInfo.vertices  =  strTemp.at(0).toInt();ondInfo.texCoords =  strTemp.at(1).toInt();ondInfo.normals   =  strTemp.at(2).toInt();}}else{ondInfo.vertices = strValues.at(i).toInt();//qDebug()<<"Face ondInfo"<<ondInfo.vertices;}facesIndexs.append(ondInfo);}}}objFile.close();int count =0;for (int i=0;i<facesIndexs.size();i++){int vIndex = facesIndexs[i].vertices - 1;if(vIndex * 3 <=vertextPoints.size() ||vIndex * 3 + 1 <=vertextPoints.size()||vIndex * 3 + 2<=vertextPoints.size() ){vPoints << vertextPoints.at(vIndex * 3);vPoints << vertextPoints.at(vIndex * 3 + 1);vPoints << vertextPoints.at(vIndex * 3 + 2);// qDebug()<<"vIndex"<<i<<vertextPoints.size()<<vIndex * 3;}else{//  qDebug()<<"vIndex error"<<i<<vertextPoints.size()<<vIndex * 3;}}vertextPoints.clear();texturePoints.clear();normalPoints.clear();facesIndexs.clear();return true;
}

 接着我们来写加载代码

和以前的一样,就是写glsl语句,

#ifndef TESTOBJOPENGL_H
#define TESTOBJOPENGL_H#include <QObject>
#include <QWidget>
#include <QOpenGLWidget>
#include <QOpenGLExtraFunctions>
#include <QOpenGLBuffer>
#include <QOpenGLShaderProgram>
#include <QOpenGLVertexArrayObject>
#include <QTimer>
#include <QOpenGLTexture>
#include <QOpenGLWidget>
#include <QOpenGLFunctions>
#include <QOpenGLBuffer>
#include <QOpenGLVertexArrayObject>
#include <QTimer>
#include <QMouseEvent>QT_FORWARD_DECLARE_CLASS(QOpenGLShaderProgram);
QT_FORWARD_DECLARE_CLASS(QOpenGLTexture)
class testobjOpengl : public QOpenGLWidget, protected QOpenGLFunctions
{
public:testobjOpengl( QWidget *parent=nullptr);~testobjOpengl();
protected:void initializeGL() override;void paintGL() override;void resizeGL(int width, int height) override;void rotateBy(int xAngle, int yAngle, int zAngle);bool load(QString fileName, QVector<float>& vPoints);struct Face{int vertices;int texCoords;int normals;Face(){vertices = -1;texCoords = -1;normals = -1;}};
private:QVector<float> m_vPoints;int m_xRot;int m_yRot;int m_zRot;QOpenGLShaderProgram *m_program= nullptr;QOpenGLVertexArrayObject vao;QOpenGLBuffer vbo;QVector3D cameraPos;QVector3D cameraTarget;QVector3D cameraDirection;QOpenGLTexture *texture;int m_projMatrixLoc;int m_mvMatrixLoc;int m_normalMatrixLoc;int m_lightPosLoc;QMatrix4x4 m_proj;QMatrix4x4 m_camera;QMatrix4x4 m_world;QVector3D m_camera_pos;QTimer* timer;int  m_yPos=0;int  m_zPos=0;};#endif // TESTOBJOPENGL_H
#include "testobjopengl.h"static const char *vertexShaderSourceCore ="#version 330\n""layout (location = 0) in vec4 vertex;\n""layout (location = 1) in vec3 normal;\n""out vec3 vert;\n""out vec3 vertNormal;\n""uniform  mat4 matrix;\n""uniform  mat4 view;\n""uniform  mat4 projection;\n""uniform  mat3 normalMatrix;\n""void main() {\n""   vert = vertex.xyz;\n""   vertNormal = normalMatrix * normal;\n""   gl_Position = projection*view* matrix * vertex;\n""}\n";
static const char *fragmentShaderSourceCore ="#version 150\n""in highp vec3 vert;\n""in highp vec3 vertNormal;\n""out highp vec4 fragColor;\n""uniform highp vec3 lightPos;\n""void main() {\n""   highp vec3 L = normalize(lightPos - vert);\n""   highp float NL = max(dot(normalize(vertNormal), L), 0.0);\n""   highp vec3 color = vec3(1.0, 1.0, 0.0);\n""   highp vec3 col = clamp(color * 0.2 + color * 0.8 * NL, 0.0, 1.0);\n""   fragColor = vec4(col, 1.0);\n""}\n";testobjOpengl::testobjOpengl(QWidget *parent): QOpenGLWidget(parent),m_xRot(0),m_yRot(0),m_zRot(0)
{m_vPoints.clear();cameraPos = QVector3D(0, 0, 3);QString strTemp = "F:/Tree2/head.obj";bool ret = load(strTemp,m_vPoints);if(ret){timer = new QTimer;timer->setInterval(100);connect(timer,&QTimer::timeout,this,[=]{qDebug()<<"timeout";rotateBy(10 * 16, +10 * 16, -1 * 16);});timer->start();}else{qDebug()<<"1111111111111111";}}
void testobjOpengl::rotateBy(int xAngle, int yAngle, int zAngle)
{float cameraSpeed = 0.2;m_camera_pos -= cameraSpeed * QVector3D(0, 0, -1);//由远到近if(m_yPos>=100){m_yPos = 0;}m_yPos+=10;if(m_zPos>=100){m_zPos = 0;}m_zPos+=10;// m_camera_pos = QVector3D(0, m_yPos, m_zPos);//由远到近// m_camera_pos.setY(m_yPos);m_xRot += xAngle;m_yRot += yAngle;m_zRot += zAngle;update();//timer->stop();
}
testobjOpengl::~testobjOpengl()
{}void testobjOpengl::initializeGL()
{initializeOpenGLFunctions();m_program = new QOpenGLShaderProgram;m_program->addShaderFromSourceCode(QOpenGLShader::Vertex, vertexShaderSourceCore);m_program->addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShaderSourceCore);if (m_program->link()){qDebug() << "link success!";}else{qDebug() << "link failed";}m_program->bindAttributeLocation("vertex", 0);m_program->bindAttributeLocation("normal", 1);m_program->link();m_program->bind();//    m_projMatrixLoc = m_program->uniformLocation("projection");
//    m_mvMatrixLoc = m_program->uniformLocation("matrix");
//    m_normalMatrixLoc = m_program->uniformLocation("normalMatrix");
//    m_lightPosLoc = m_program->uniformLocation("lightPos");vbo.create();vbo.bind();vbo.allocate(m_vPoints.data(), m_vPoints.size() * sizeof(float));QOpenGLFunctions *f = QOpenGLContext::currentContext()->functions();f->glEnableVertexAttribArray(0);f->glEnableVertexAttribArray(1);f->glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), nullptr);f->glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), reinterpret_cast<void *>(3 * sizeof(GLfloat)));vbo.release();m_program->setUniformValue(m_lightPosLoc, QVector3D(10, 10, 10)); 
}void testobjOpengl::paintGL()
{glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);glEnable(GL_DEPTH_TEST);glEnable(GL_CULL_FACE);QMatrix4x4 m;//m.ortho(-0.5f, +0.5f, +0.5f, -0.5f, 4.0f, 15.0f);m.setToIdentity();m.translate(0.0f, 0.0f, 0.0f);m.rotate(m_xRot / 16.0f, 1.0f, 0.0f, 0.0f);m.rotate(90, 0.0f, 1.0f, 0.0f);m.rotate(0, 0.0f, 0.0f, 1.0f);m.scale(0.5);QMatrix4x4 view;view.setToIdentity();view.lookAt(QVector3D(0, 20, 20), QVector3D(0,0,0), QVector3D(1,0,0));m_program->bind();m_program->setUniformValue("projection", m_proj);m_program->setUniformValue("matrix", m);m_program->setUniformValue("view", view);m_program->setUniformValue("lightPos", QVector3D(10, 10, 0));QMatrix3x3 normalMatrix = m.normalMatrix();m_program->setUniformValue("normalMatrix", normalMatrix);glDrawArrays(GL_TRIANGLES, 0, m_vPoints.size()/3);m_program->release();
}void testobjOpengl::resizeGL(int width, int height)
{m_proj.setToIdentity();m_proj.perspective(45.0f, GLfloat(width) / height, 0.01f, 100.0f);
}
bool testobjOpengl::load(QString fileName, QVector<float>& vPoints)
{if (fileName.mid(fileName.lastIndexOf('.')) != ".obj" && fileName.mid(fileName.lastIndexOf('.')) != ".OBJ"){qDebug() << "file is not a obj file.";return false;}QFile objFile(fileName);if (!objFile.open(QIODevice::ReadOnly)){qDebug() << "open" << fileName << "failed";return false;}else{qDebug() << "open" << fileName << "success!";}QVector<float> vertextPoints, texturePoints, normalPoints;QVector<Face> facesIndexs;while (!objFile.atEnd()){QByteArray lineData = objFile.readLine();QList<QByteArray> strValues = lineData.trimmed().split(' ');QString dataType = strValues.takeFirst();for(int i=0;i<strValues.size();i++){double nData = strValues.at(i).toDouble();QString strTemp = QString::number(nData,'f',4);if (dataType == "v"){vertextPoints.append(strTemp.toFloat());}else if (dataType == "vt"){texturePoints.append(strValues.at(i).toFloat());}else if (dataType == "vn"){normalPoints.append(strValues.at(i).toFloat());}else if (dataType == "f"){Face ondInfo;if(strValues.at(i).contains("/")){QList<QByteArray> strTemp = strValues.at(i).split('/');if(strTemp.size()==2){ondInfo.vertices  =  strTemp.at(0).toInt();ondInfo.texCoords =  strTemp.at(1).toInt();}else if(strTemp.size()==3){ondInfo.vertices  =  strTemp.at(0).toInt();ondInfo.texCoords =  strTemp.at(1).toInt();ondInfo.normals   =  strTemp.at(2).toInt();}}else{ondInfo.vertices = strValues.at(i).toInt();//qDebug()<<"Face ondInfo"<<ondInfo.vertices;}facesIndexs.append(ondInfo);}}}objFile.close();int count =0;for (int i=0;i<facesIndexs.size();i++){int vIndex = facesIndexs[i].vertices - 1;if(vIndex * 3 <=vertextPoints.size() ||vIndex * 3 + 1 <=vertextPoints.size()||vIndex * 3 + 2<=vertextPoints.size() ){vPoints << vertextPoints.at(vIndex * 3);vPoints << vertextPoints.at(vIndex * 3 + 1);vPoints << vertextPoints.at(vIndex * 3 + 2);// qDebug()<<"vIndex"<<i<<vertextPoints.size()<<vIndex * 3;}else{//  qDebug()<<"vIndex error"<<i<<vertextPoints.size()<<vIndex * 3;}}vertextPoints.clear();texturePoints.clear();normalPoints.clear();facesIndexs.clear();return true;
}

 我们开始调用

testobjOpengl w;

w.show();

运行结果:

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/news/899101.shtml
繁体地址,请注明出处:http://hk.pswp.cn/news/899101.shtml
英文地址,请注明出处:http://en.pswp.cn/news/899101.shtml

如若内容造成侵权/违法违规/事实不符,请联系英文站点网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

0326-Java 字符串方法

package com.qc.字符串;import java.util.Arrays;public class Test {public static void main(String[] args) { // String x"hello";//字符串 char[] // x x"demo";//字符串拼接 // xx2450; // xxtrue; // System.out.println(x);//hellodemo2450t…

<command-line>:0:1: error: macro names must be identifiers m

报错&#xff1a;:0:1: error: macro names must be identifiers 排查类很久 原来是&#xff1a; add_compile_definitions(_GLIBCXX_USE_CXX11_ABI$ABI_VERSION)写成了 add_compile_definitions(-D_GLIBCXX_USE_CXX11_ABI$ABI_VERSION)多了个 -D。

风光互补智慧路灯的灯杆设计有哪些要求?

嘿&#xff0c;朋友们&#xff01;叁仟风光互补智慧路灯的灯杆设计那可是超级重要的事儿&#xff0c;得全方位综合考量各种因素&#xff0c;就是为了确保咱们的路灯能兼具超棒的功能性、绝对的安全性、无敌的美观性以及超厉害的耐用性&#xff01;下面就来看看这些超赞的常见要…

06、RAG

LLM的知识仅限于它所接受到的训练数据。如果我们希望让它了解特定领域的专有知识&#xff0c;则可以使用下面的方式操作&#xff1a; 使用RAG使用专有数据对LLM进行微调RAG与数据微调方式结合使用 什么是RAG 简单地说&#xff0c;RAG就是把数据发送给LLM之前从数据中查找相关…

自然语言处理:第一百零二章 如何去掉DeepSeek R1思考过程

本人项目地址大全&#xff1a;Victor94-king/NLP__ManVictor: CSDN of ManVictor 写在前面: 笔者更新不易&#xff0c;希望走过路过点个关注和赞&#xff0c;笔芯!!! 写在前面: 笔者更新不易&#xff0c;希望走过路过点个关注和赞&#xff0c;笔芯!!! 写在前面: 笔者更新不易…

flink 安装与访问 ui

官方文档&#xff1a;First steps | Apache Flink 版本&#xff1a;v2.0.0 下载Flink Flink运行在所有类UNIX环境中&#xff0c;即Linux&#xff0c;Mac OS X和Cygwin&#xff08;适用于Windows&#xff09;。您需要安装Java 11。要检查安装的Java版本&#xff0c;请在终端中…

WPF TextBox实现键盘enter后实时读取TextBox中的值

代码 <TextBox Grid.Column"0" x:Name"textBox" Margin"10,5,0,5" TextWrapping"Wrap" Text"{Binding SendMessage,UpdateSourceTriggerPropertyChanged}" VerticalContentAlignment"Center" CaretBrush&qu…

PyTorch实现Transformer模型

首先&#xff0c;我得回顾一下Transformer的基本结构&#xff0c;确保自己没有记错。Transformer由编码器和解码器组成&#xff0c;每个编码器层包含多头自注意力机制和前馈网络&#xff0c;解码器层则还有编码器-解码器注意力。 接下来&#xff0c;用户需要的是手把手的代码解…

详细介绍sentinel的使用,并列举经常出的面试题以及答案

Sentinel 是一款由阿里巴巴开源的分布式系统的流量防卫系统&#xff0c;能够实时响应并满足高并发的流量控制需求。它提供了流量监控、流量控制、熔断降级、系统保护等核心功能&#xff0c;可帮助开发人员实时发现系统的流量异常并快速做出相应的限流策略。 Sentinel 的使用步…

mysql-connector-java-5.1.37.jarJava连接器

mysql-connector-java-5.1.37.jar是MySQL官方提供的Java连接器&#xff0c;用于在Java应用程序中与MySQL数据库进行通信。具体来说&#xff0c;这个JAR文件是MySQLJDBC驱动程序的一个版本&#xff0c;允许Java程序通过JDBC&#xff08;JavaDatabaseConnectivity&#xff09;接口…

Python基于Django的智能旅游推荐系统(附源码,文档说明)

博主介绍&#xff1a;✌IT徐师兄、7年大厂程序员经历。全网粉丝15W、csdn博客专家、掘金/华为云//InfoQ等平台优质作者、专注于Java技术领域和毕业项目实战✌ &#x1f345;文末获取源码联系&#x1f345; &#x1f447;&#x1f3fb; 精彩专栏推荐订阅&#x1f447;&#x1f3…

【博客节选】再谈Unity 的 root motion

节选自 【Unity实战笔记】第二十三 root motion变更方向攻击 &#xff08;OnStateMove rootmotion rigidbody 使用的一些问题&#xff09; 小伙伴们应该对root motion非常困惑&#xff0c;包括那个bake into pose。 当xz bake into pose后&#xff0c;角色攻击动画与父节点产…

网站服务器常见的CC攻击防御秘籍!

CC攻击对网站的运营是非常不利的&#xff0c;因此我们必须积极防范这种攻击&#xff0c;但有些站长在防范这种攻击时可能会陷入误区。让我们先了解下CC攻击&#xff01; CC攻击是什么 CC是DDoS攻击的一种&#xff0c;CC攻击是借助代理服务器生成指向受害主机的合法请求&#x…

JAVA:Spring Boot @Conditional 注解详解及实践

1、简述 在 Spring Boot 中&#xff0c;Conditional 注解用于实现 条件化 Bean 装配&#xff0c;即根据特定的条件来决定是否加载某个 Bean。它是 Spring 框架中的一个扩展机制&#xff0c;常用于实现模块化、可配置的组件加载。 本文将详细介绍 Conditional 相关的注解&…

使用python爬取网络资源

整体思路 网络资源爬取通常分为以下几个步骤&#xff1a; 发送 HTTP 请求&#xff1a;使用requests库向目标网站发送请求&#xff0c;获取网页的 HTML 内容。解析 HTML 内容&#xff1a;使用BeautifulSoup库解析 HTML 内容&#xff0c;从中提取所需的数据。处理数据&#xff…

PostgreSQL 数据库源码编译安装全流程详解 Linux 8

PostgreSQL 数据库源码编译安装全流程详解 Linux 8 1. 基础环境配置1.1 修改主机名1.2 配置操作系统yum源1.3 安装操作系统依赖包1.4 禁用SELINUX配置1.5 关闭操作系统防火墙1.6 创建用户和组1.7 建立安装目录1.8 编辑环境变量 2. 源码方式安装&#xff08;PG 16&#xff09;2.…

(基本常识)C++中const与引用——面试常问

作者&#xff1a;求一个demo 版权声明&#xff1a;著作权归作者所有&#xff0c;商业转载请联系作者获得授权&#xff0c;非商业转载请注明出处 内容通俗易懂&#xff0c;没有废话&#xff0c;文章最后是面试常问内容&#xff08;建议通过标题目录学习&#xff09; 废话不多…

Java并发编程 什么是分布式锁 跟其他的锁有什么区别 底层原理 实战讲解

目录 一、分布式锁的定义与核心作用 二、分布式锁与普通锁的核心区别 三、分布式锁的底层原理与实现方式 1. 核心实现原理 2. 主流实现方案对比 3. 关键技术细节 四、典型问题与解决方案 五、总结 六、具体代码实现 一、分布式锁的定义与核心作用 分布式锁是一种在分布…

案例:使用网络命名空间模拟多主机并通过网桥访问外部网络

案例目标 隔离性&#xff1a;在同一台物理机上创建两个独立的网络命名空间&#xff08;模拟两台主机&#xff09;&#xff0c;确保其网络配置完全隔离。内部通信&#xff1a;允许两个命名空间通过虚拟设备直接通信。外部访问&#xff1a;通过宿主机的网桥和 NAT 规则&#xff…

AF3 Rotation 类解读

Rotation 类(rigid_utils 模块)是 AlphaFold3 中用于 3D旋转 的核心组件,支持两种旋转表示: 1️⃣ 旋转矩阵 (3x3) 2️⃣ 四元数 (quaternion, 4元向量) 👉 设计目标: 允许灵活选择 旋转矩阵 或 四元数 封装了常用的 旋转操作(组合、逆旋转、应用到点上等) 像 torch.…