美文网首页
4.1案例-模型视图投影矩阵

4.1案例-模型视图投影矩阵

作者: bytebytebyte | 来源:发表于2020-11-28 09:28 被阅读0次
    #include "GLTools.h"
    #include "GLMatrixStack.h"
    #include "GLFrame.h"
    #include "GLFrustum.h"
    #include "GLGeometryTransform.h"
    #include "GLBatch.h"
    #include "StopWatch.h"
    
    #include <math.h>
    #ifdef __APPLE__
    #include <glut/glut.h>
    #else
    #define FREEGLUT_STATIC
    #include <GL/glut.h>
    #endif
    
    GLFrustum viewFrustum;
    GLShaderManager shaderManager;
    GLTriangleBatch torusBatch;
    GLGeometryTransform transformPipeline;
    
    //窗口改变时接受新的宽度和高度,0,0代表窗口中视口的左下角坐标,w,h代表像素
    void ChangeSize(int w, int h) {
        //防止除以0
        if (h == 0) {
            h = 1;
        }
        glViewport(0, 0, w, h);
        viewFrustum.SetPerspective(35, float(w) / float(h) , 1, 1000); //设置透视投影
    }
    
    //开始渲染
    void renderScene(void) {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        //建立基于时间变化的动画
        static CStopWatch rotTimer;
        //当前时间*60s
        float yRot = rotTimer.GetElapsedSeconds() * 60;
        //平移 旋转 视图 视图投影MVP
        M3DMatrix44f mTranslate, mRotate, mModelView, mModelViewProjection;
        //创建一个4*4矩阵变量,将花托沿着z轴复负方向移动2.5个单位长度
        m3dTranslationMatrix44(mTranslate, 0, 0, -2.5);
        //创建一个4*4矩阵变量,将花托在y轴上渲染yRot度,yRot根据经过时间设置动画帧率 也可设置x轴
        m3dRotationMatrix44(mRotate, m3dDegToRad(yRot), 0, 1, 0);
        //mTranslate 和mRotate 相乘放到 mModelView
        m3dMatrixMultiply44(mModelView, mTranslate, mRotate);
        //投影*模型!=模型*投影
        m3dMatrixMultiply44(mModelViewProjection, viewFrustum.GetProjectionMatrix(), mModelView);
        
        GLfloat vBlack[] = { 0, 0, 0, 1 };
        //通过平面着色器提交矩阵和颜色
        shaderManager.UseStockShader(GLT_SHADER_FLAT, mModelViewProjection, vBlack);
        //开始绘图
        torusBatch.Draw();
        //交换缓冲区
        glutSwapBuffers();
        //刷新
        glutPostRedisplay();
        
    }
    
    //为程序做一次性的设置
    void setupRC() {
        glClearColor(0.8, 0.8, 0.8, 1);
        shaderManager.InitializeStockShaders();
        glEnable(GL_DEPTH_TEST);
        
        //形成一个球
        gltMakeSphere(torusBatch, 0.4, 10, 20);
        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
    }
    
    int main(int argc, char *argv[]) {
        gltSetWorkingDirectory(argv[0]);
        glutInit(&argc, argv);
        glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL);
        glutInitWindowSize(800, 600);
        glutCreateWindow("ModelViewProjection Example");
        glutReshapeFunc(ChangeSize);
        glutDisplayFunc(renderScene);
        GLenum err = glewInit();
        if (err != GLEW_OK) {
            fprintf(stderr, "GLEW Error:%s\n",glewGetErrorString(err));
            return 1;
        }
        setupRC();
        glutMainLoop();
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:4.1案例-模型视图投影矩阵

          本文链接:https://www.haomeiwen.com/subject/szwuiktx.html