graphics

experiments with opengl3.2/ogles3.3 on linux and win7
git clone http://frotz.net/git/graphics.git
Log | Files | Refs

Model.cc (1888B)


      1 /* Copyright 2013 Brian Swetland <swetland@frotz.net>
      2  *
      3  * Licensed under the Apache License, Version 2.0 (the "License");
      4  * you may not use this file except in compliance with the License.
      5  * You may obtain a copy of the License at
      6  *
      7  *     http://www.apache.org/licenses/LICENSE-2.0
      8  *
      9  * Unless required by applicable law or agreed to in writing, software
     10  * distributed under the License is distributed on an "AS IS" BASIS,
     11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     12  * See the License for the specific language governing permissions and
     13  * limitations under the License.
     14  */
     15 
     16 #include <string>
     17 
     18 #include "Model.h"
     19 
     20 #include "stringutils.h"
     21 #include "util.h"
     22 
     23 // idx, src, dst, count, offset, stride, divisor
     24 static VertexAttrDesc layout[] = {
     25 	{ 0, SRC_FLOAT, DST_FLOAT, 3,  0, 32, 0 },
     26 	{ 1, SRC_FLOAT, DST_FLOAT, 3, 12, 32, 0 },
     27 	{ 2, SRC_FLOAT, DST_FLOAT, 2, 24, 32, 0 },
     28 };
     29 
     30 void Model::render(void) {
     31 	attr.use();
     32 	texture.use(0);
     33 	glDrawElements(GL_TRIANGLES, icount, GL_UNSIGNED_SHORT, NULL);
     34 }
     35 
     36 int Model::init(const char *name) {
     37 	string128 fname(name);
     38 	int len = fname.length();
     39 	struct model *m;
     40 	VertexBuffer *data[] = {
     41 		&vbuf, &vbuf, &vbuf,
     42 	};
     43 
     44 	fname.append(".obj");
     45 	if (!(m = load_wavefront_obj(fname)))
     46 		return error("cannot load model");
     47 
     48 	printx("Object '%s' loaded. %d vertices, %d indices.\n",
     49 		name, m->vcount, m->icount);
     50 
     51 	fname.trim(len).append(".png");
     52 	texture.load(fname, OPT_TEX2D_GEN_MIPMAP);
     53 
     54 	vbuf.load(m->vdata, 32 * m->vcount);
     55 	ibuf.load(m->idx, 2 * m->icount);
     56 
     57 	icount = m->icount;
     58 
     59 	attr.init(layout, data, sizeof(layout)/sizeof(layout[0]));
     60 
     61 	/* this will persist because it is part of the VAO state */
     62 	ibuf.use();
     63 
     64 	delete_wavefront_obj(m);
     65 
     66 	return 0;
     67 }
     68 
     69 Model *Model::load(const char *name) {
     70 	Model *m = new Model();
     71 	if (m->init(name)) {
     72 		delete m;
     73 		return nullptr;
     74 	} else {
     75 		return m;
     76 	}
     77 }
     78