一个类中的OpenGL函数

问题描述 投票:-1回答:1

我正在创建一个包含ParticleFactory类的OpenGL项目,用于在场景中生成粒子。

为了实现这一点,我创建了一个类:

#ifndef PARTICLE_H
#define PARTICLE_H

#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <iostream> 
#include <vector>
#include "vertex.h"

#include <shader_s.h>

class ParticleFactory {
    public:
        Shader* shader;
        std::vector<Particle> particles;
        unsigned int VAO, VBO, EBO;
        unsigned int nr_particles;

        ParticleFactory(unsigned int nr_particles, unsigned int color){
            Shader sh("shaders/particle.vs", "shaders/particle.fs");
            shader = &sh;
            this->nr_particles = nr_particles;
            for(unsigned int i = 0; i < nr_particles; i++) {
                float x = (rand()%200)/100.0 - 1;
                float y = (rand()%200)/100.0 - 1;
                float z = (rand()%200)/100.0 - 1;
                particles.push_back(Particle(glm::vec4(x, y, z, 0.0)));
            }

            glGenVertexArrays(1, &VAO);
            glGenBuffers(1, &VBO);
            glGenBuffers(1, &EBO);
            glBindVertexArray(VAO);
            glBindBuffer(GL_ARRAY_BUFFER, VBO);
            glBufferData(GL_ARRAY_BUFFER, sizeof(base_particle), base_particle, GL_STREAM_DRAW);
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
            glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(base_particle_indices), base_particle_indices, GL_STREAM_DRAW);
            glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
            glEnableVertexAttribArray(0);
        }

        void draw() {
            shader->use();
            shader->setMat4("model", model);
            shader->setMat4("view", view);
            shader->setMat4("projection", projection);
            shader->setMat4("transform", transform);
            for (int i=0; i<nr_particles; i++) {
                shader->setVec4("offset", particles[i].offset);
                glBindVertexArray(VAO);
                glDrawElements(GL_TRIANGLES, 24, GL_UNSIGNED_INT, 0);
                particles[i].offset += glm::vec4(0.0f, -0.001f, 0.0f, 0.0f);
                if (particles[i].offset.y <= -1.0f) {
                    particles[i].offset.y = 1.0f;
                }
            }
        }
};

#endif

我的方法是首先实例化一个对象,然后在主循环上调用.draw(),但它似乎不起作用,我不知道为什么。

c++ opengl glfw glm-math
1个回答
0
投票

在我们进入OpenGL部分之前,您要创建一个LOCAL对象(sh),然后将其地址分配给着色器成员。在构造函数的末尾,sh将被删除,因此着色器成员将指向...?首先,您需要使用new / delete(或者更好的是,使用std :: unique_ptr <Shader>)以确保在您想要使用它时对象仍然存在。

先试试吧!

© www.soinside.com 2019 - 2024. All rights reserved.