m_particles是我要绘制的大量的实体图形容器。其中包含了图形的位置,大小,颜色,在纹理图片上的区域等信息。m_texture是图形纹理
如果是单独绘制她们,是使用下面的办法
virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const{
for(auto &any:m_particles){
sf::RectangleShape rs;
//设置纹理图形
rs.setTexture(&m_texture);
//位置
rs.setPosition(sf::Vector2f(any.Position));
//设置显示的纹理区域
rs.setTextureRect(any.TextureRect);
//图形大小
rs.setSize(sf::Vector2f(any.Size));
//用颜色填充,可以实现改变纹理的颜色
rs.setFillColor(any.Color);
//绘制
target.draw(rs,states);
}
}如果图形数量很多,上面的方法每次都会单独调用显卡绘制,很低效。会加重显卡负担。所以使用顶点数组的办法绘制这些图形,可以一次性批量将图形绘制到显卡。
下面的代码实现了同样的效果。并且减少了资源的消耗。
virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const{
sf::VertexArray verticles;
verticles.setPrimitiveType(sf::Triangles);//设置图元类型为三角形
for(auto &any:m_particles){
sf::Vertex vertex_0,vertex_1,vertex_2,vertex_3,vertex_4,vertex_5;
vertex_0.color = any.Color;
vertex_1.color = any.Color;
vertex_2.color = any.Color;
vertex_3.color = any.Color;
vertex_4.color = any.Color;
vertex_5.color = any.Color;
vertex_0.position = sf::Vector2f(any.Position.x,any.Position.y);
vertex_1.position = sf::Vector2f(any.Position.x,any.Position.y+any.Size.y);
vertex_2.position = sf::Vector2f(any.Position.x+any.Size.x,any.Position.y);
vertex_3.position = sf::Vector2f(any.Position.x+any.Size.x,any.Position.y);
vertex_4.position = sf::Vector2f(any.Position.x,any.Position.y+any.Size.y);
vertex_5.position = sf::Vector2f(any.Position.x+any.Size.x,any.Position.y+any.Size.y);
vertex_0.texCoords = sf::Vector2f(any.TextureRect.left,any.TextureRect.top);
vertex_1.texCoords = sf::Vector2f(any.TextureRect.left,any.TextureRect.top+any.TextureRect.height);
vertex_2.texCoords = sf::Vector2f(any.TextureRect.left+any.TextureRect.width,any.TextureRect.top);
vertex_3.texCoords = sf::Vector2f(any.TextureRect.left+any.TextureRect.width,any.TextureRect.top);
vertex_4.texCoords = sf::Vector2f(any.TextureRect.left,any.TextureRect.top+any.TextureRect.height);
vertex_5.texCoords = sf::Vector2f(any.TextureRect.left+any.TextureRect.width,any.TextureRect.top+any.TextureRect.height);
verticles.append(vertex_0);
verticles.append(vertex_1);
verticles.append(vertex_2);
verticles.append(vertex_3);
verticles.append(vertex_4);
verticles.append(vertex_5);
}
states.texture = &m_texture;
target.draw(verticles,states);
}sf::VertexArray是顶点数组。sf::Vertex是顶点元素,储存顶点的颜色,位置和纹理坐标。上面的代码,在每一个图形我做的事情就是用6个顶点也就是2个三角形表示。每个顶点设置颜色信息。设置位置信息和对应纹理上的纹理坐标。让纹理能够正确的贴合到这2个三角形上。这2个三角形拼接成一个矩形、能够正确的显示形状。