模板操作,提供了一些技巧的空间,要实现各种效果,模板是一个好工具.随着看书,写了一些代码.先画一个小三角形,相应的模板值设为1,再画一个大三角形,参考值大于模板值的通过测试,可以继续绘制,效果就是一个大三角形套着小三角形.
// Stencil.cpp -- 2013/11/20-21:38 #include "stdafx.h" #include <GLTools.h> #include <GLShaderManager.h> #define FREEGLUT_STATIC #include <GL/glut.h> GLBatch smallTriangleBatch; GLBatch bigTriangleBatch; GLShaderManager shaderManager; void ChangeSize(int w, int h) { glViewport(0, 0, w, h); } void SetupRC() { glClearColor(0.0f, 0.0f, 1.0f, 1.0f ); shaderManager.InitializeStockShaders(); GLfloat vSmallVerts[] = { -0.5f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f }; smallTriangleBatch.Begin(GL_TRIANGLES, 3); smallTriangleBatch.CopyVertexData3f(vSmallVerts); smallTriangleBatch.End(); GLfloat vBigVerts[] = { -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f }; bigTriangleBatch.Begin(GL_TRIANGLES, 3); bigTriangleBatch.CopyVertexData3f(vBigVerts); bigTriangleBatch.End(); glEnable(GL_STENCIL_TEST); } void RenderScene(void) { glClearStencil(0) ; glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); // 总是通过模板测试,用参考值按位与掩码值. 0x01 & 0xff = 0x1 glStencilFuncSeparate(GL_FRONT, GL_ALWAYS, 1, 0xff) ; // 第2,3,4个参数依次为:模板测试失败时的动作,深度测试失败时的动作,深度测试通过时的动作 glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_KEEP, GL_REPLACE) ; GLfloat vRed[] = { 1.0f, 0.0f, 0.0f, 1.0f }; shaderManager.UseStockShader(GLT_SHADER_IDENTITY, vRed); smallTriangleBatch.Draw(); // 参考值(1)大于模板缓冲区的值则通过测试 glStencilFuncSeparate(GL_FRONT, GL_GREATER, 1, 0xff) ; glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_KEEP, GL_KEEP) ; GLfloat vGreen[] = {0, 1.0f, 0, 1.0f} ; shaderManager.UseStockShader(GLT_SHADER_IDENTITY, vGreen) ; bigTriangleBatch.Draw() ; glutSwapBuffers(); } int main(int argc, char* argv[]) { gltSetWorkingDirectory(argv[0]); glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_STENCIL); glutInitWindowSize(800, 600); glutCreateWindow("Triangle"); 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; }
入行2年了,不知道算长算短,也不知道自己走得算不算远,还好一直在走,也按着自己的步伐在走,还算是不错.加油吧,加油~