您的位置:首页 > 编程语言 > C#

CSharpGL(2)设计和使用场景元素及常用接口

2015-09-01 15:39 459 查看
[b]CSharpGL(2)设计和使用场景元素及常用接口 [/b]

主要内容

描述在OpenGL中绘制场景的思路。

设计场景元素的抽象基类SceneELementBase。

以PyramidElement为例演示SceneELementBase的用法。

下载

您可以在(https://github.com/bitzhuwei/CSharpGL)找到最新的源码。欢迎感兴趣的同学fork之。

public static class IUILayoutRenderingHelper
{
private static readonly object synObj = new object();
private static EventHandler<RenderEventArgs> simpleUIAxis_BeforeRendering = null;
private static EventHandler<RenderEventArgs> simpleUIAxis_AfterRendering = null;

/// <summary>
/// 对Xxx : SceneElementBase, IUILayout, IMVP有效的After事件。
/// <para>此处用泛型方法是为了让编译器检测where约束条件,这样就没有“坑”了。</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="element"></param>
/// <returns></returns>
public static EventHandler<RenderEventArgs> GetSimpleUI_AfterRendering<T>(this T element)
where T : SceneElementBase, IUILayout, IMVP
{
if (simpleUIAxis_AfterRendering == null)
{
lock (synObj)
{
if (simpleUIAxis_AfterRendering == null)
{
simpleUIAxis_AfterRendering = new EventHandler<RenderEventArgs>(SimpleUI_AfterRendering);
}
}
}

return simpleUIAxis_AfterRendering;
}

/// <summary>
/// 对Xxx : SceneElementBase, IUILayout, IMVP有效的Before事件。
/// <para>此处用泛型方法是为了让编译器检测where约束条件,这样就没有“坑”了。</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="element"></param>
/// <returns></returns>
public static EventHandler<RenderEventArgs> GetSimpleUI_BeforeRendering<T>(this T element)
where T : SceneElementBase, IUILayout, IMVP
{
if (simpleUIAxis_BeforeRendering == null)
{
lock (synObj)
{
if (simpleUIAxis_BeforeRendering == null)
{
simpleUIAxis_BeforeRendering = new EventHandler<RenderEventArgs>(SimpleUI_BeforeRendering);
}
}
}

return simpleUIAxis_BeforeRendering;
}

static void SimpleUI_AfterRendering(object sender, RenderEventArgs e)
{
IMVP element = sender as IMVP;
element.ResetShaderProgram();
}

static void SimpleUI_BeforeRendering(object sender, RenderEventArgs e)
{
mat4 projectionMatrix, viewMatrix, modelMatrix;
{
IUILayout element = sender as IUILayout;
element.GetMatrix(out projectionMatrix, out viewMatrix, out modelMatrix, e.Camera);
}

{
IMVP element = sender as IMVP;
element.SetShaderProgram(projectionMatrix * viewMatrix * modelMatrix);
}
}
}


IUILayoutRenderingHelper

借助扩展方法、类型约束等等机制,编写OpenGL程序效率高了很多。

下面是效果图。下图中,在窗口的四个角落各安排了1个SimpUIRect。无论Camera如何改变,窗口大小如何改变,这四个蓝色矩形框的大小、边距都不会改变。



总结

本篇是写起来最有难度的一篇。本篇所实现的类型、接口,都是在上一篇的基础上设计的。上一篇里讲的渲染过程,隐含着本篇的设计方案的前提条件。

本篇里的类型、接口都有各自的一套辅助类型构成一套实现某种功能的机制。但愿这不太复杂难用。我已经用Demo详细演示了各个功能是如何实现的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: