
#include "global.h"

CMD2::CMD2 ()
{
	triangle = NULL;
	frame = NULL;
	m_iFrames = m_iVertices = m_iTriangles = 0;
}

CMD2::~CMD2 ()
{
	int i;
	if (frame != NULL) 
      {
		for (i = 0; i < m_iFrames; i++)
			delete [] frame[i].vertex;
		delete [] frame;
	   }
	if (triangle != NULL)
		delete [] triangle;
}

void CMD2::Destroy (void)
{
	int i;
	if (frame != NULL) 
      {
		for (i = 0; i < m_iFrames; i++)
			delete [] frame[i].vertex;
		delete [] frame;
		frame = NULL;
	   }
	if (triangle != NULL) 
      {
		delete [] triangle;
		triangle = NULL;
	   }
	m_iFrames = 0;
}

int CMD2::Read (char filename[])
{
	FILE		*modelfile = NULL;
	char		g_skins[MAX_MD2SKINS][64];
	dstvert_t	base_st[MAX_VERTS];
	byte		buffer[MAX_VERTS*4+128];
	dmdl_t		modelheader;

	dtriangle_t     tri;
	daliasframe_t	*out;

	int i, j;

	if ((modelfile = fopen (filename, "rb")) == NULL)
		return 0;

	SafeRead (modelfile, &modelheader, sizeof(modelheader));

	modelheader.framesize = (int)&((daliasframe_t *)0)->verts[modelheader.num_xyz];

	////////////////////////////////////////////////////

	m_iFrames		= modelheader.num_frames;
	m_iVertices		= modelheader.num_xyz;
	m_iTriangles	= modelheader.num_tris;

	triangle = new make_triangle [modelheader.num_tris];
	frame = new make_frame [modelheader.num_frames];

	for (i = 0; i < modelheader.num_frames; i++)
		frame[i].vertex = new make_vertex_list [modelheader.num_xyz];

	////////////////////////////////////////////////////

	SafeRead (modelfile, g_skins, modelheader.num_skins * MAX_SKINNAME);

	SafeRead (modelfile, base_st, modelheader.num_st * sizeof(base_st[0]));

	for (i = 0; i < modelheader.num_tris; i++) {
		SafeRead (modelfile, &tri, sizeof(dtriangle_t));

		(triangle)[i].a = tri.index_xyz[0];
		(triangle)[i].b = tri.index_xyz[1];
		(triangle)[i].c = tri.index_xyz[2];

		(triangle)[i].a_s = base_st[tri.index_st[0]].s;
		(triangle)[i].a_t = base_st[tri.index_st[0]].t;
		(triangle)[i].b_s = base_st[tri.index_st[1]].s;
		(triangle)[i].b_t = base_st[tri.index_st[1]].t;
		(triangle)[i].c_s = base_st[tri.index_st[2]].s;
		(triangle)[i].c_t = base_st[tri.index_st[2]].t;
	}

/*
   if (modelheader.num_frames > 1)
      {
      //EngineError("Number of frames for %s is %d. File must have only one frame.", filename, modelheader.num_frames);
      }
*/
      
	for (i = 0; i < modelheader.num_frames; i++) {

		out = (daliasframe_t *)buffer;

		SafeRead (modelfile, out, modelheader.framesize);

		for (j = 0; j < modelheader.num_xyz; j++) {

			(frame)[i].vertex[j].x = out->verts[j].v[1] * out->scale[1] + out->translate[1];
			(frame)[i].vertex[j].y = out->verts[j].v[2] * out->scale[2] + out->translate[2];
			(frame)[i].vertex[j].z = -out->verts[j].v[0] * out->scale[0] - out->translate[0];
		}
		strcpy((frame)[i].name, out->name);
	}

	fclose (modelfile);
	return 1;
}
