CSharpGL(46)用Billboard绘制头顶文字

本文介绍CSharpGL用Billboard绘制头顶文字的方法。效果如下图所示。

下载

CSharpGL已在GitHub开源,欢迎对OpenGL有兴趣的同学加入(https://github.com/bitzhuwei/CSharpGL

固定大小的Billboard

在OpenGL的渲染流水线上,描述顶点位置的坐标,依次要经过object space, world space, view/camera space, clip space, normalized device space, Screen/window space这几个状态。下表列出了各个状态的特点。

Space

Coordinate

feature

object

(x, y, z, 1)

从模型中读取的原始位置(x,y,z),可在shader中编辑

world

(x, y, z, w)

可在shader中编辑

view/camera

(x, y, z, w)

可在shader中编辑

clip

(x, y, z, w)

vertex shader中,赋给gl_Position的值

normalized device

(x, y, z, 1)

上一步的(x, y, z, w)同时除以w。OpenGL自动完成。x, y, z的绝对值小于1时,此顶点在窗口可见范围内。即可见范围为[-1, -1, -1]到[1, 1, 1]。

screen/window

glViewport(x, y, width, height);

glDepthRange(near, far)

窗口左下角为(0, 0)。

上一步的顶点为(-1, -1, z)时,screen上的顶点为(x, y)。

上一步的顶点为(1, 1, z)时,screen上的顶点为(width, height)。

为了让Billboard保持他应有的位置和深度值,object space, world space, view space这三步是必须照常进行的。

在normalized device space这个状态下,[-1,-1,-1]和[1,1,1]之间就是Billboard能显示出来的部分。例如,如果一个Billboard矩形的四个角落,恰好落在(-1,-1)和(1,1)上,那么这个Billboard就会恰好覆盖整个画布。所以,如果知道了Billboard和画布的尺寸(像素值),就可以按比例计算出Billboard在此状态时应有的尺寸了。

这两段分析就是下面的vertex shader的精髓。Billboard的位置,由一个位于矩形中心的点表示。在object space里,这个点自然要位于(0, 0, 0, 1)。

 #version  core

 uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform mat4 modelMatrix;
uniform vec2 screenSize; // screen size in pixels. uniform float width; // Billboard’s width in pixels
uniform float height;// Billboard’s height in pixels. in vec2 inPosition;// character's quad's position relative to left bottom(0, 0).
in vec3 inSTR;// character's quad's texture coordinate. out vec3 passSTR; void main(void) {
vec4 position = projectionMatrix * viewMatrix * modelMatrix * vec4(, , , );
position = position / position.w;// 代替OpenGL pipeline除以w的步骤。
position.xy += (inPosition * height - vec2(width, height)) / screenSize;
gl_Position = position; passSTR = inSTR;
}

绘制文字

首先,你要知道如何准备文字Texture(参考这里)。

然后,根据给定的字符串Text,找到各个char的位置,更新positionBuffer和uvBuffer,更新Billboard的Width和Height。为了减少客户端的计算量,在安排char的位置时,是从左下角(0,0)开始,到右上角(width, height)结束的。不然,就该把char的位置整体移动到以(0,0)为中心了。

下图中,把一个一个字符围起来的框框,说明了文字是如何排列的。

多个Billboard的重叠问题

在Billboard中,为了显示文字,启用了OpenGL的混合(blend)功能。

         public static TextBillboardNode Create(int width, int height, int capacity, GlyphServer glyphServer = null)
{
var vs = new VertexShader(vertexCode);// this vertex shader has no vertex attributes.
var fs = new FragmentShader(fragmentCode);
var provider = new ShaderArray(vs, fs);
var map = new AttributeMap();
map.Add(inPosition, GlyphsModel.position);
map.Add(inSTR, GlyphsModel.STR);
// 启用混合功能
var blendState = new BlendState(BlendingSourceFactor.SourceAlpha, BlendingDestinationFactor.OneMinusSourceAlpha);
var builder = new RenderMethodBuilder(provider, map, blendState);
var node = new TextBillboardNode(width, height, new GlyphsModel(capacity), builder, glyphServer);
node.Initialize(); return node;
}

由于blend功能是与渲染顺序相关的(即渲染顺序不同,产生的结果就可能不同),所以在渲染多个Billboard时,就可能产生不好的效果:近处的Billboard可能遮挡住远处的。

为了解决这个问题,我想了一个办法:先按深度给各个Billboard排序,然后依序渲染各个Billboard。为此,需要新建一些东西。

排序动作BillboardSortAction

首先要将各个Billboard排序,并保存到数组。显然,在这里,使用二分插入排序是最快的排序方式。

     public class BillboardSortAction : DependentActionBase
{
private List<float> depthList = new List<float>();
private List<TextBillboardNode> billboardList = new List<TextBillboardNode>(); /// <summary>
/// Sorted billboard list.
/// </summary>
public List<TextBillboardNode> BillboardList
{
get { return billboardList; }
} /// <summary>
/// Sort billboards in depth order.
/// </summary>
/// <param name="scene"></param>
public BillboardSortAction(Scene scene) : base(scene) { } public override void Act()
{
this.depthList.Clear();
this.billboardList.Clear(); mat4 viewMatrix = this.Scene.Camera.GetViewMatrix();
this.Sort(this.Scene.RootElement, viewMatrix);
} private void Sort(SceneNodeBase sceneElement, mat4 viewMatrix)
{
if (sceneElement != null)
{
var billboard = sceneElement as TextBillboardNode;
if (billboard != null)
{
Insert(billboard, viewMatrix);
} foreach (var item in sceneElement.Children)
{
this.Sort(item, viewMatrix);
}
}
} /// <summary>
/// binary insertion sort.
/// </summary>
/// <param name="billboard"></param>
/// <param name="camera"></param>
/// <param name="list"></param>
private void Insert(TextBillboardNode billboard, mat4 viewMatrix)
{
// viewPosition.z is depth in view/camera space.
vec3 viewPosition = billboard.GetAbsoluteViewPosition(viewMatrix);
int left = , right = this.depthList.Count - ;
while (left <= right)
{
int middle = (left + right) / ;
float value = this.depthList[middle];
if (value < viewPosition.z)
{
left = middle + ;
}
else if (value == viewPosition.z)
{
left = middle;
break;
}
else //(viewPosition.z < value)
{
right = middle - ;
}
} this.depthList.Insert(left, viewPosition.z);
this.billboardList.Insert(left, billboard);
}
}

BillboardSortAction

渲染动作BillboardRenderAction

虽然我们有专门的渲染动作RenderAction,但是RenderAction只会按结点的树结构顺次渲染。因此,我们要新建一个专门渲染已经排序好了的Billboard数组的动作。

     /// <summary>
/// Render sorted billboards.
/// </summary>
public class BillboardRenderAction : DependentActionBase
{
private BillboardSortAction sortAction;
public BillboardRenderAction(Scene scene, BillboardSortAction sortAction)
: base(scene)
{
this.sortAction = sortAction;
} public override void Act()
{
var arg = new RenderEventArgs(this.Scene, this.Scene.Camera);
foreach (var item in this.sortAction.BillboardList)
{
item.RenderBeforeChildren(arg);
}
}
}
}

当然,不要忘了取消Billboard在RenderAction里的渲染动作。

     var billboard = TextBillboardNode.Create(, , );
billboard.Text = string.Format("Hello TextBillboardNode[{0}]!", index);
// we don't render it in RenderAction. we render it in BillboardRenderAction.
billboard.EnableRendering = ThreeFlags.None;

总结

又一次,又一次,又一次,犯了很二的错误。

TextBillboardNode.cs是复制过来的,然后我就忘记了修改里面的AttributeMap的数据。原本2个小时就能完成的东西,花了2天才找到错误所在。

这个事情告诉我,即使很类似的代码,也不要复制过来。一点一点写才是最快的。

最新文章

  1. 关于HTML的FORM上传文件问题
  2. Python第十二章正则表达式(2)
  3. 有趣的insert死锁
  4. POJ 3422Kaka&#39;s Matrix Travels(最小费用最大流)
  5. 对中级Linux用户有用的20个命令
  6. mac上xampp配置
  7. H264码流解析及NALU
  8. APK downloader
  9. PostgreSQL Replication之扩展与BDR
  10. jQuery基本知识
  11. Masonry1.0.2 源码解析
  12. Python&#160;date,datetime,time等相关操作总结
  13. P1914 一串字母
  14. git 删除本地所有分支
  15. dom2级事件兼容性写法
  16. Nginx下SSL证书设置和反向代理
  17. day03作业
  18. Python全栈day14(字符串格式化)
  19. Windows下IIS+PHP 5.2的安装与配置
  20. jQuery判断表单input

热门文章

  1. datalist 分页
  2. 微信小程序开发框架技术选型
  3. 微信小程序-获取经纬度
  4. Putty连接TPYBorad v102 开发板教程
  5. 创建ndarray
  6. CDN及CDN加速原理
  7. MyBatis缓存详解
  8. 二十四、Hadoop学记笔记————Spark的架构
  9. python3中用HTMLTestRunner.py报ImportError: No module named &#39;StringIO&#39;解决办法
  10. 简历HTML网页版