3 This file is part of libmspgl
4 Copyright © 2007 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
9 #include "vertexarray.h"
10 #include "vertexbuffer.h"
17 uint get_stride(VertexFormat f)
20 for(uint fmt=f; fmt; fmt>>=4)
22 return stride*sizeof(float);
26 VertexArrayBuilder::VertexArrayBuilder(VertexArray &a, vector<float> &d):
29 format(array.get_format()),
30 stride(get_stride(format)),
31 cr(1), cg(1), cb(1), ca(1),
32 ts(0), tt(0), tr(0), tq(0),
36 void VertexArrayBuilder::vertex(float x, float y, float z, float w)
38 for(uint fmt=format; fmt; fmt>>=4)
46 if(size>=3) data.push_back(z);
47 if(size>=4) data.push_back(w);
56 if(size>=2) data.push_back(tt);
57 if(size>=3) data.push_back(tr);
58 if(size>=4) data.push_back(tq);
63 union { ubyte c[4]; float f; } u;
64 u.c[0]=(ubyte)(cr*255);
65 u.c[1]=(ubyte)(cg*255);
66 u.c[2]=(ubyte)(cb*255);
67 u.c[3]=(ubyte)(ca*255);
75 if(size>=4) data.push_back(ca);
80 //cout<<"Added vertex with "<<data.size()-old_size<<" floats\n";
83 VertexArrayBuilder::~VertexArrayBuilder()
89 VertexArray::VertexArray(VertexFormat f):
91 stride(get_stride(f)),
95 // Reverse the format so the first item is in lowest bits
96 for(uint fmt=f; fmt; fmt>>=4)
97 format=(format, static_cast<VertexFormat>(fmt&15));
100 VertexArray::~VertexArray()
106 void VertexArray::use_vertex_buffer()
110 vbuf=new VertexBuffer();
115 void VertexArray::use_vertex_buffer(VertexBuffer *b)
123 void VertexArray::clear()
128 void VertexArray::apply() const
130 if(vbuf) vbuf->bind();
132 const float *base=vbuf?0:&data[0];
135 for(uint fmt=format; fmt; fmt>>=4)
141 glVertexPointer(size, GL_FLOAT, stride, base+offset);
144 glNormalPointer(GL_FLOAT, stride, base+offset);
147 glTexCoordPointer(size, GL_FLOAT, stride, base+offset);
151 glColorPointer(4, GL_UNSIGNED_BYTE, stride, base+offset);
153 glColorPointer(size, GL_FLOAT, stride, base+offset);
156 found|=1<<((fmt&12)>>2);
160 set_array(GL_VERTEX_ARRAY, found&1, 1);
161 set_array(GL_NORMAL_ARRAY, found&2, 2);
162 set_array(GL_TEXTURE_COORD_ARRAY, found&4, 4);
163 set_array(GL_COLOR_ARRAY, found&8, 8);
165 VertexBuffer::unbind();
169 Updates the VertexArray data to the VertexBuffer tied to the array, if any.
171 void VertexArray::update_data()
174 vbuf->data(data.size()*sizeof(float), &data[0]);
177 void VertexArray::set_array(unsigned array, unsigned bit, unsigned mask) const
179 if((enabled_arrays&mask) && !bit)
181 glDisableClientState(array);
182 enabled_arrays&=~mask;
184 else if(!(enabled_arrays&mask) && bit)
186 glEnableClientState(array);
187 enabled_arrays|=mask;
191 unsigned VertexArray::enabled_arrays=0;