OpenGL(OpenTK)学习

绘制一个Cube
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void glControl1_Resize(object sender, EventArgs e) { //改变大小时触发的事件,在程序启动时将会触发一次 GLControl c = sender as GLControl; //获取glControl1 if (glControl1.ClientSize.Height == 0) //避免错误 glControl1.ClientSize = new Size(glControl1.ClientSize.Width, 1); GL.Viewport(0, 0, glControl1.ClientSize.Width, glControl1.ClientSize.Height); //设置3D绘画的画布 float aspect_ratio = Width / (float)Height; Matrix4 perpective = Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspect_ratio, 1, 64); //设置4x4的变换矩阵 GL.MatrixMode(MatrixMode.Projection); GL.LoadMatrix(ref perpective); //加载矩阵 } private void glControl1_Paint(object sender, PaintEventArgs e) { //重绘事件,在刷新程序GUI时触发,在程序启动时将会触发一次 Matrix4 lookat = Matrix4.LookAt(0, 5, 5, 0, 0, 0, 0, 1, 0); GL.MatrixMode(MatrixMode.Modelview); GL.LoadMatrix(ref lookat); //旋转变换,这是视图的调整 GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); //清空画布 DrawCube(); glControl1.SwapBuffers(); //清除缓存 } protected override void OnLoad(EventArgs e) //重写Form.OnLoad { base.OnLoad(e); //触发原本的OnLoad GL.ClearColor(Color.White); //清空画布,并用Color.White填充画布 GL.Enable(EnableCap.DepthTest); //深度测试 glControl1_Resize(glControl1, EventArgs.Empty); //触发Resize事件 } /* GL.Color3 => 设置顶点颜色GL.Vertex3 => 设置顶点位置 GL.Begin(BeginMode.Quads) => Quads是多边形模式 GL.End() => 用这个结束绘画 这段代码看似为顶点着色,其实是因为Quads的影响让顶点内部填充了颜色。 你们也许会觉得很奇怪,为什么上面的调用后面都有“3”呢?这是GL的形式: gl[过程名称][参数数量][参数类型](参数); //在OpenTk里就没有参数类型这个了,所以GL.Vertex3(...);在非OpenTK里就应该这样写glVertex3f(...); 也就是说:GL.Vertex3后面将会传递3个参数 * */ private void DrawCube() { GL.Begin(BeginMode.Quads); GL.Color3(Color.Silver); GL.Vertex3(-1.0f, -1.0f, -1.0f); GL.Vertex3(-1.0f, 1.0f, -1.0f); GL.Vertex3(1.0f, 1.0f, -1.0f); GL.Vertex3(1.0f, -1.0f, -1.0f); GL.Color3(Color.Honeydew); GL.Vertex3(-1.0f, -1.0f, -1.0f); GL.Vertex3(1.0f, -1.0f, -1.0f); GL.Vertex3(1.0f, -1.0f, 1.0f); GL.Vertex3(-1.0f, -1.0f, 1.0f); GL.Color3(Color.Moccasin); GL.Vertex3(-1.0f, -1.0f, -1.0f); GL.Vertex3(-1.0f, -1.0f, 1.0f); GL.Vertex3(-1.0f, 1.0f, 1.0f); GL.Vertex3(-1.0f, 1.0f, -1.0f); GL.Color3(Color.IndianRed); GL.Vertex3(-1.0f, -1.0f, 1.0f); GL.Vertex3(1.0f, -1.0f, 1.0f); GL.Vertex3(1.0f, 1.0f, 1.0f); GL.Vertex3(-1.0f, 1.0f, 1.0f); GL.Color3(Color.PaleVioletRed); GL.Vertex3(-1.0f, 1.0f, -1.0f); GL.Vertex3(-1.0f, 1.0f, 1.0f); GL.Vertex3(1.0f, 1.0f, 1.0f); GL.Vertex3(1.0f, 1.0f, -1.0f); GL.Color3(Color.ForestGreen); GL.Vertex3(1.0f, -1.0f, -1.0f); GL.Vertex3(1.0f, 1.0f, -1.0f); GL.Vertex3(1.0f, 1.0f, 1.0f); GL.Vertex3(1.0f, -1.0f, 1.0f); GL.End(); } }

  

原文地址:https://www.cnblogs.com/DragonX/p/3468062.html