zoukankan      html  css  js  c++  java
  • [Modern OpenGL系列(三)]用OpenGL绘制一个三角形

    本文已同步发表在CSDN:http://blog.csdn.net/wenxin2011/article/details/51347008


    上一篇文章中已经介绍了OpenGL窗口的创建。本文接着说如何用OpenGL绘制一个三角形。
    1 . 添加头文件mesh.h,代码如下:

    #pragma once
    
    #include <glmglm.hpp>
    #include <GLglew.h>
    
    class Vertex
    {
    public:
    	Vertex(const glm::vec3& pos)
    	{
    		this->pos = pos;
    	}
    protected:
    private:
    	glm::vec3 pos;
    };
    
    class Mesh
    {
    public:
    	Mesh(Vertex* vertices, unsigned int numVertices);
    
    	void Draw();
    	
    	virtual ~Mesh();
    
    protected:
    private:
    	Mesh(const Mesh& other);
    	void operator=(const Mesh& other);
    
    	enum
    	{
    		POSITION_VB,
    		NUM_BUFFERS
    	};
    
    	GLuint m_vertexArrayObject;
    	GLuint m_vertexArrayBuffers[NUM_BUFFERS];
    	unsigned int m_drawCount;
    };
    

    2 . 添加类mesh.cpp,代码如下:

    #include "mesh.h"
    
    Mesh::Mesh(Vertex* vertices, unsigned int numVertices)
    {
    	m_drawCount = numVertices;
    
    	glGenVertexArrays(1, &m_vertexArrayObject);
    	glBindVertexArray(m_vertexArrayObject);
    
    	glGenBuffers(NUM_BUFFERS, m_vertexArrayBuffers);
    	glBindBuffer(GL_ARRAY_BUFFER, m_vertexArrayBuffers[POSITION_VB]);
    	glBufferData(GL_ARRAY_BUFFER, numVertices * sizeof(vertices[0]),  vertices, GL_STATIC_DRAW);
    	
    	glEnableVertexAttribArray(0);
    	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
    
    	glBindVertexArray(0);
    }
    
    Mesh::~Mesh()
    {
    	glDeleteVertexArrays(1, &m_vertexArrayObject);
    }
    
    void Mesh::Draw()
    {
    	glBindVertexArray(m_vertexArrayObject);
    	glDrawArrays(GL_TRIANGLES, 0, m_drawCount);
    
    	glBindVertexArray(0);
    }
    

    3 . 修改主类main.cpp,代码如下:

    #include <GLglew.h>
    #include "display.h"
    #include "mesh.h"
    
    int main(int argc, char** argv)
    {
    	// 设置窗体大小和标题
    	Display display(400, 300, "hello world!");
    
    	// 设置三角形顶点
    	Vertex vertices[] = { Vertex(glm::vec3(-0.5, -0.5, 0)), Vertex(glm::vec3(0, 0.5, 0)), Vertex(glm::vec3(0.5, -0.5, 0)), };
    
    	// 生成网格
    	Mesh mesh(vertices, sizeof(vertices) / sizeof(vertices[0]));
    
    	while (!display.IsClosed())
    	{
    		display.Clear(0.0f, 1.0f, 0.0f, 1.0f);
    
    		// 绘制三角形
    		mesh.Draw();	
    
    		display.Update();// 刷新
    	}
    
    	return 0;
    }
    

    本文整理自YouTube视频教程#3.5 Intro to Modern OpenGL Tutorial: Meshes


    声明:本文欢迎转载和分享,但是请尊重作者的劳动成果,转载分享时请注明出处:http://www.cnblogs.com/davidsheh/p/5471193.html 。同时,码字实在不易,如果你觉得笔者分享的笔记对你有点用处,请顺手点击下方的推荐,谢谢!

  • 相关阅读:
    JAVA-容器(5)-Map
    JAVA-容器(4)-Set
    数据脏读-非重复读-幻读
    JAVA-容器(3)-List
    JAVA-容器(2)-Collection
    JAVA-容器(1)
    Arrays排序
    JAVA-虚拟机(3)-调优
    zip解压缩
    rabbitMQ、activeMQ、zeroMQ、Kafka、Redis 比较
  • 原文地址:https://www.cnblogs.com/davidsheh/p/5471193.html
Copyright © 2011-2022 走看看