/* $Id$
This file is part of libmspgl
-Copyright © 2007 Mikko Rasa, Mikkosoft Productions
+Copyright © 2007-2010 Mikko Rasa, Mikkosoft Productions
Distributed under the LGPL
*/
#include "buffer.h"
+#include "extension.h"
#include "mesh.h"
using namespace std;
Mesh::Mesh():
vertices(VERTEX3),
- ibuf(0)
+ ibuf(0),
+ defer_ibuf(true)
{ }
Mesh::Mesh(const VertexFormat &f):
vertices(f),
- ibuf(0)
+ ibuf(0),
+ defer_ibuf(true)
{ }
-void Mesh::use_vertex_buffer(bool b)
+Mesh::~Mesh()
+{
+ delete ibuf;
+}
+
+void Mesh::clear()
+{
+ vertices.clear();
+ batches.clear();
+}
+
+void Mesh::use_buffers(bool b)
{
if(b)
{
vertices.use_vertex_buffer();
if(!ibuf)
- ibuf=new Buffer(ELEMENT_ARRAY_BUFFER);
- update_index_buffer();
+ ibuf = new Buffer(ELEMENT_ARRAY_BUFFER);
+ defer_ibuf = false;
}
else
{
vertices.use_vertex_buffer(0);
delete ibuf;
- ibuf=0;
+ ibuf = 0;
+ defer_ibuf = false;
}
}
-float *Mesh::get_vertex(unsigned i)
+unsigned Mesh::get_n_vertices() const
{
- return vertices[i];
+ return vertices.size();
}
-void Mesh::add_batch(const Batch &b)
+float *Mesh::modify_vertex(unsigned i)
{
- batches.push_back(b);
- update_index_buffer();
+ return vertices.modify(i);
}
-void Mesh::clear()
+void Mesh::add_batch(const Batch &b)
{
- vertices.clear();
- batches.clear();
-}
+ bool can_append = false;
+ if(!batches.empty())
+ {
+ PrimitiveType type = b.get_type();
+ can_append = (type==batches.back().get_type() &&
+ type!=LINE_STRIP && type!=LINE_LOOP && type!=POLYGON &&
+ (type!=TRIANGLE_FAN || is_supported("GL_NV_primitive_restart")));
+ }
-void Mesh::draw() const
-{
- vertices.apply();
- if(ibuf)
+ if(defer_ibuf)
{
- ibuf->bind();
- unsigned offset=0;
- for(list<Batch>::const_iterator i=batches.begin(); i!=batches.end(); ++i)
- {
- i->draw_with_buffer(offset);
- offset+=i->size();
- }
- ibuf->unbind();
+ ibuf = new Buffer(ELEMENT_ARRAY_BUFFER);
+ defer_ibuf = false;
}
+
+ if(can_append)
+ batches.back().append(b);
else
{
- for(list<Batch>::const_iterator i=batches.begin(); i!=batches.end(); ++i)
- i->draw();
+ Batch *prev = (batches.empty() ? 0 : &batches.back());
+ batches.push_back(b);
+ if(ibuf)
+ batches.back().use_index_buffer(ibuf, prev);
}
}
-void Mesh::update_index_buffer()
+void Mesh::draw() const
{
- if(!ibuf)
- return;
+ vertices.apply();
- unsigned total=0;
- for(list<Batch>::const_iterator i=batches.begin(); i!=batches.end(); ++i)
- total+=i->size();
+ if(ibuf)
+ ibuf->bind_to(ELEMENT_ARRAY_BUFFER);
- ibuf->data(total*sizeof(unsigned), 0);
- unsigned offset=0;
for(list<Batch>::const_iterator i=batches.begin(); i!=batches.end(); ++i)
- {
- ibuf->sub_data(offset*sizeof(unsigned), i->size()*sizeof(unsigned), &i->get_indices()[0]);
- offset+=i->size();
- }
- ibuf->unbind();
+ i->draw();
+
+ if(ibuf)
+ Buffer::unbind_from(ELEMENT_ARRAY_BUFFER);
}
void Mesh::Loader::batch(PrimitiveType p)
{
- obj.batches.push_back(Batch(p));
- load_sub(obj.batches.back());
+ Batch btc(p);
+ load_sub(btc);
+ obj.add_batch(btc);
}
} // namespace GL