[迁移]opengl学习从头开始(笔记15 粒子效果)

声明:因网易博客将关闭,移到此

/**
    这里使用到的是opengl 和 glut 进行编写学习的笔记,一个简单的出口
    使用到的开发库有 linux (gl glu glut) windows(opengl32.lib glu32.lib glut32.lib)

    实现: 粒子效果

    例子:
        这里使用的是raw作为粒子的纹理,(raw 读取没有具体去看,不知道是否其他有不相同
        这个是用nehe第19课拿出来的,可以去
http://nehe.gamedev.net/tutorial/particle_engine_using_triangle_strips/21001/)

     键盘部分
        方向键,上下,左右,分别控制粒子的x,y加速度
        home键初始化粒子
        end 控制控制颜色
        w,s 控制y方向的速度
        a,d 控制x方向的速度    
        pageup,pagedown 控制z方向
        q,e 控制速度

        还有其他键,那要自己去看代码了,^_^
        
        
    问题:
        1.如果我要绘制粒子我又要绘制各种3D物体那怎么办呢?
            当你绘制模型,又添加了粒子会发现怪怪的地方,那就是
            粒子关闭了深度测试,而绘制3D我体又要打开,
            在绘制模型的时候打开深度测试,在使用粒子的时候关闭深度测试
        
            ...看代码吧,(*^__^*) 嘻嘻……

*/

#include 
#include 
#include 
#include 

#ifdef _MSC_VER

#endif

#ifdef __GNUC__
#include 
#endif

#define MAX_PARTICLES 1000

using namespace std;

// 图片的类型 包含宽 高 数据
struct Image
{
    unsigned long sizeX;
    unsigned long sizeY;
    char *data;
};
typedef struct Image Image;

// 
static GLfloat g_colors[12][3] = 
{
    {1.0f,0.5f,0.5f},{1.0f,0.75f,0.5f},{1.0f,1.0f,0.5f},{0.75f,1.0f,0.5f},
    {0.5f,1.0f,0.5f},{0.5f,1.0f,0.75f},{0.5f,1.0f,1.0f},{0.5f,0.75f,1.0f},
    {0.5f,0.5f,1.0f},{0.75f,0.5f,1.0f},{1.0f,0.5f,1.0f},{1.0f,0.5f,0.75f}
};

// 存储粒子的结构体
struct particles
{
    bool active;    // 
    float life;        // 粒子的生命
    float fade;        // 粒子衰减速度
    float x,y,z;    // 粒子的位置
    float r,g,b;    // 粒子的颜色
    float xi,yi,zi;    // 粒子的速度
    float xg,yg,zg;    // 粒子的加速度
};

particles particle[MAX_PARTICLES];

// 我们用来旋转下模型吧
GLuint g_texture;
GLuint g_btexture;

float g_angle = 0;
float g_zoom = -40;
float g_slowdown = 2.0f;

float g_xspeed;
float g_yspeed;

int i;
GLuint col = 0;
GLuint g_delay;

bool g_rainbow = true;    // 彩虹
bool g_sp;                // 空格?
bool g_rp;                // enter?

bool keys[512];


// 下面是读取自定义格式的模型信息文件使用的函数


//----------------------------------------------------------
// 读取图片文件
int ImageLoad(const char *filename, Image *image)
{
    FILE *file;
    unsigned long size; // 图片长度
    unsigned long i;    // 计数
    unsigned short int planes;
    unsigned short int bpp;
    char temp;            // bgr -rgb 变换

    if ((file = fopen(filename, "rb")) == NULL)
    {
        printf("File Not Found: %s\n", filename);
        return 0;
    }

    // 跳过文件的头部,准备读取宽度和高度
    // 如果想自己具体的情况可以去看看bmp图片的相关信息
    fseek(file, 18, SEEK_CUR);

    // 读取宽度
    if ((i = fread(&image->sizeX, 4, 1, file)) != 1)
    {
        printf("Error reading width from %s. \n", filename);
        return 0;
    }
    printf("Width of %s: %lu\n", filename, image->sizeX);
    
    // 读取宽度
    if ((i = fread(&image->sizeY, 4, 1, file)) != 1)
    {
        printf("Error reading height from %s. \n", filename);
        return 0;
    }
    printf("Height of %s: %lu\n", filename, image->sizeY);

    // 计算长度(24bits或3bytes每个像素)
    size = image->sizeX * image->sizeY * 3;

    // 读取
    if ((fread(&planes, 2, 1, file)) != 1)
    {
        printf("Error reading planes from %s. \n", filename);
        return 0;
    }

    if (planes != 1)
    {
        printf("Planes from %s is not 1: %u\n", filename, planes);
        return 0;
    }

    if ((i = fread(&bpp, 2, 1, file)) != 1)
    {
        printf("Error reading bpp from %s. \n", filename);
        return 0;
    }
    if (bpp != 24)
    {
        printf("Bpp from %s is not 24: %u\n", filename, bpp);
        return 0;
    }

    // 跳过余下的头文件数据
    fseek(file, 24, SEEK_CUR);

    // 读取数据
    image->data = (char*) malloc (size);
    if (image->data == NULL)
    {
        printf("Error allocating memory for color-corrected image data");
        return 0;
    }

    if ((i = fread(image->data, size, 1, file)) != 1)
    {
        printf("Error reading image data from %s. \n", filename);
        return 0;
    }

    // 交换颜色 bgr -> rgb
    for (i = 0; i < size; i += 3)
    {
        temp = image->data[i];
        image->data[i] = image->data[i+2];
        image->data[i+2] = temp;
    }

    // 完成
    return 1;
}

// 读取 bitmaps 并转化成纹理
void LoadGLTextures(const std::string& picname, GLuint& texture)
{
    Image *image1;
    image1 = (Image*) malloc (sizeof(Image));
    
    if (image1 == NULL)
    {
        printf("Error allocating space for image");
        exit(0);
    }    

    if (!ImageLoad(picname.c_str(), image1))
        exit(1);
    // 创建纹理
    // 线性滤波
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture); // 绑定2D纹理
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

    glTexImage2D(GL_TEXTURE_2D, 0, 3, image1->sizeX, image1->sizeY,
            0, GL_RGB, GL_UNSIGNED_BYTE, image1->data);

    free(image1);
}

int LoadGLRawTextures(const std::string& picname, GLuint& texture)
{
    int status;
    GLubyte *tex = new GLubyte[32 * 32 * 3];
    FILE *tf;

    tf = fopen("Particle.raw", "rb");
    fread(tex, 1, 32 * 32 * 3, tf);
    fclose(tf);

    status = 1;
    glGenTextures(1, &texture);

    glBindTexture(GL_TEXTURE_2D, texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, 3, 32, 32, 0, GL_RGB, GL_UNSIGNED_BYTE, tex);

    delete [] tex;
    return status;
}
//===========================OpenGL 部分=========================
// 初始化opengl的一些参数
void init()
{
    // 设置灯光
    GLfloat LightAmbient[] = {0.5f, 0.5f, 0.5f, 1.0f}; // 环境光参数
    GLfloat LightDiffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f}; // 漫反射光参数
    GLfloat LightPosition[] = { 2.0f, 8.0f, 1.0f, 1.0f}; // 光源位置

    glLightfv(GL_LIGHT1, GL_AMBIENT, LightAmbient); // 设置环境光
    glLightfv(GL_LIGHT1, GL_DIFFUSE, LightDiffuse); // 设置漫反射光
    glLightfv(GL_LIGHT1, GL_POSITION, LightPosition); // 设置位置

    glEnable(GL_LIGHT1);
    LoadGLRawTextures("Particle.raw",g_texture);
    LoadGLTextures("glass.bmp",g_btexture);

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // 清理背景颜色为蓝色
    glClearDepth(1.0);                    
    glDepthFunc(GL_LESS);
    glShadeModel(GL_SMOOTH);
    glEnable(GL_POINT_SMOOTH);
    glEnable(GL_LINE_SMOOTH);
    glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); // 使用圆点而不使用方点    
    glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);    // Antialias the lines
    glEnable(GL_BLEND);
    //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC1_ALPHA);
    // 粒子系统用到了混合哦
    glBlendFunc(GL_SRC_ALPHA, GL_ONE);
    //glEnable(GL_DEPTH_TEST);
    glEnable(GL_TEXTURE_2D);

    //glBindTexture(GL_TEXTURE_2D, g_texture);

    // 生成粒子群
    for (i = 0; i < MAX_PARTICLES; i++)
    {
        particle[i].active = true;
        particle[i].life = 1.0f;
        particle[i].fade = float(rand() % 100) / 100.0f + 0.003f;
        particle[i].r = g_colors[i * (12 /MAX_PARTICLES)][0]; 
        particle[i].g = g_colors[i * (12 /MAX_PARTICLES)][1]; 
        particle[i].b = g_colors[i * (12 /MAX_PARTICLES)][2]; 

        // 设置粒子的速度
        particle[i].xi = float((rand() % 50) - 26.0f) * 10.0f; 
        particle[i].yi = float((rand() % 50) - 25.0f) * 10.0f; 
        particle[i].zi = float((rand() % 50) - 25.0f) * 10.0f; 

        // 设置粒子的加速度
        particle[i].xg = 0.0f;
        particle[i].yg = -0.8f;
        particle[i].zg = 0.0f;
    }    
}

//------------------------------------
// 设置刷新时间
void timer(int p)
{
    glutPostRedisplay();
    glutTimerFunc(20, timer, 0);
}

//-----------------------------------
void check_keys()
{
    if (keys['q'] && (g_slowdown > 0.0f)) g_slowdown -= 0.01f;
    if (keys['e'] && (g_slowdown < 4.0f)) g_slowdown += 0.01f;

    if (keys[GLUT_KEY_PAGE_UP]) g_zoom += 0.1f;
    if (keys[GLUT_KEY_PAGE_DOWN]) g_zoom -= 0.1f;

    if (keys[GLUT_KEY_END] && !g_rp)
    {
        g_rp = true;
        g_rainbow = !g_rainbow;
    }

    if (!keys[GLUT_KEY_END]) g_rp = false;
    if ((keys[' '] && !g_sp) || (g_rainbow && (g_delay > 25)))
    {
        if (keys[' ']) g_rainbow = false;
        g_sp = true;
        g_delay = 0;
        col++;
        if (col > 11) col = 0;
    }

    if (!keys[' ']) g_sp = true;
    if (keys['w'] && (g_yspeed < 200)) g_yspeed += 1.0f;
    if (keys['s'] && (g_yspeed > -200)) g_yspeed -= 1.0f;
    if (keys['a'] && (g_xspeed < 200)) g_xspeed += 1.0f;
    if (keys['d'] && (g_xspeed > -200)) g_xspeed -= 1.0f;

    g_delay++;
}

//-----------------------------------
// 显示我们要绘制的模型
void display()
{
 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // 清理颜色缓存和深度缓存
 glLoadIdentity(); // 重置矩阵

 glTranslatef(0.0f, 0.0f, -20.0f);

 glPushMatrix();
 glRotatef(g_angle, 1.0f, 1.0f, 0.0f);

 g_angle ++;

 glDisable(GL_BLEND);
 glEnable(GL_DEPTH_TEST);
 glBindTexture(GL_TEXTURE_2D, g_btexture);
 glColor3f(1.0f, 1.0f, 1.0f);
 glBegin(GL_QUADS);
    // 前面
    glNormal3f(0.0f, 0.0f, 1.0f);
    glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); // left top
    glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f,-1.0f, 1.0f); // left bottom
    glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f,-1.0f, 1.0f); // right bottom 
    glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f); // right top

    // 后面
    glNormal3f(0.0f, 0.0f, -1.0f);
    glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); // left top
    glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); // right top
    glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f,-1.0f, -1.0f); // right bottom 
    glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f,-1.0f, -1.0f); // left bottom

    // 左面
    glNormal3f(-1.0f, 0.0f, 0.0f);
    glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); // left top
    glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f); // left bottom
    glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); // right bottom 
    glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); // right top

    // 右面
    glNormal3f(1.0f, 0.0f, 0.0f);
    glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f); // left top
    glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f,-1.0f, 1.0f); // left bottom
    glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f,-1.0f, -1.0f); // right bottom 
    glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); // right top

    // 上面
    glNormal3f(0.0f, 1.0f, 0.0f);
    glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); // left top
    glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, 1.0f, 1.0f); // left bottom
    glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, 1.0f, 1.0f); // right bottom 
    glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); // right top

    // 下面
    glNormal3f(0.0f, -1.0f, 0.0f);
    glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f,-1.0f, -1.0f); // left top
    glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f,-1.0f, 1.0f); // left bottom
    glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f,-1.0f, 1.0f); // right bottom 
    glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f,-1.0f,-1.0f); // right top
 glEnd();
 glDisable(GL_DEPTH_TEST);
 glEnable(GL_BLEND);

 glPopMatrix();

 glPushMatrix();
 glTranslatef(-6.0f, 0.0f, 0.0f);
 glTranslatef(6.0f, 0.0f, 0.0f);

 check_keys();

 glBindTexture(GL_TEXTURE_2D, g_texture);
 for (i = 0; i < MAX_PARTICLES; i++)
 {
     if (particle[i].active)
     {
         float x = particle[i].x;
         float y = particle[i].y;
         float z = particle[i].z + g_zoom;

         glColor4f(particle[i].r, particle[i].g, particle[i].b, particle[i].life);
         glBegin(GL_TRIANGLE_STRIP);
          glTexCoord2d(1, 1); glVertex3f(x + 0.5f, y + 0.5f, z); // 右上
          glTexCoord2d(0, 1); glVertex3f(x - 0.5f, y + 0.5f, z); // 左上
          glTexCoord2d(1, 0); glVertex3f(x + 0.5f, y - 0.5f, z); // 右下
          glTexCoord2d(0, 0); glVertex3f(x - 0.5f, y - 0.5f, z); // 左下
         glEnd();
        
         // 更新位置
         particle[i].x += particle[i].xi / (g_slowdown * 1000);
         particle[i].y += particle[i].yi / (g_slowdown * 1000);
         particle[i].z += particle[i].zi / (g_slowdown * 1000);

         // 更新速度
         particle[i].xi += particle[i].xg;
         particle[i].yi += particle[i].yg;
         particle[i].zi += particle[i].zg;
        
         // 速度
         particle[i].life -= particle[i].fade;

         if (particle[i].life < 0.0f)
         {
             particle[i].life = 1.0f;
             particle[i].fade = float(rand() % 100) / 1000.0f + 0.003f;

             particle[i].x = 0.0f;
             particle[i].y = 0.0f;
             particle[i].z = 0.0f;

             particle[i].xi = g_xspeed + float((rand() % 60) - 32.0f);
             particle[i].yi = g_yspeed + float((rand() % 60) - 30.0f);
             particle[i].zi = float((rand() % 60) - 30.0f);

             particle[i].r = g_colors[col][0];
             particle[i].g = g_colors[col][1];
             particle[i].b = g_colors[col][2];

         }
         
         if (keys[GLUT_KEY_UP] && (particle[i].yg < 1.5f)) particle[i].yg += 0.01f;
         if (keys[GLUT_KEY_DOWN] && (particle[i].yg > -1.5f)) particle[i].yg -= 0.01f;
         if (keys[GLUT_KEY_LEFT] && (particle[i].xg < 1.5f)) particle[i].yg += 0.01f;
         if (keys[GLUT_KEY_RIGHT] && (particle[i].xg > -1.5f)) particle[i].yg -= 0.01f;

         if (keys[GLUT_KEY_HOME])
         {
             particle[i].x = 0.0f;
             particle[i].y = 0.0f;
             particle[i].z = 0.0f;

             particle[i].xi = float((rand() % 50) - 26.0f) * 1.0f;
             particle[i].yi = float((rand() % 50) - 25.0f) * 1.0f;
             particle[i].zi = float((rand() % 50) - 25.0f) * 1.0f;
         }

     }
 }
 /*
 glBegin(GL_TRIANGLES); // 开始绘制三角形
    glVertex3f( 0.1f,  1.0f, 0.0f);
    glVertex3f(-1.0f, -1.0f, 0.0f);
    glVertex3f( 1.0f, -1.0f, 0.0f);
 glEnd();
*/
 glPopMatrix();

 glutSwapBuffers(); //双缓冲
}

//-----------------------------------
// 当窗口变化的时候会调用这里
void reshape(int w, int h)
{
    /* 视口设置
     * 这个是当窗口发生大小变化的时候会调用这里,大家可以自己
     * 拉伸下窗口就可以看到不一样的地方了
     */
    glViewport(0, 0, (GLsizei) w, (GLsizei) h); // 设置视口
    glMatrixMode(GL_PROJECTION); // 设置当前矩阵为投影矩阵
    glLoadIdentity();

    if (h == 0) h = 1; // 防止除0情况
    gluPerspective(45.0f,(GLfloat) w / (GLfloat)h , 0.5f, -1000.0f);

    glMatrixMode(GL_MODELVIEW); // 设置当前矩阵为模型矩阵
    glLoadIdentity();
}

//-----------------------------------
//键盘事件
void keyboarddown(unsigned char key, int x, int y)
{
    if (key < 512)
        keys[key] = true;

    //cout<

你可能感兴趣的:([迁移]opengl学习从头开始(笔记15 粒子效果))