RAS_Polygon* RAS_MeshObject::AddPolygon(RAS_MaterialBucket *bucket, int numverts)
{
	RAS_MeshMaterial *mmat;
	RAS_Polygon *poly;
	RAS_MeshSlot *slot;

	/* find a mesh material */
	mmat = GetMeshMaterial(bucket->GetPolyMaterial());

	/* none found, create a new one */
	if (!mmat) {
		RAS_MeshMaterial meshmat;
		meshmat.m_bucket = bucket;
		meshmat.m_baseslot = meshmat.m_bucket->AddMesh(numverts);
		meshmat.m_baseslot->m_mesh = this;
		m_materials.push_back(meshmat);
		mmat = &m_materials.back();
	}

	/* add it to the bucket, this also adds new display arrays */
	slot = mmat->m_baseslot;
	slot->AddPolygon(numverts);

	/* create a new polygon */
	RAS_DisplayArray *darray = slot->CurrentDisplayArray();
	poly = new RAS_Polygon(bucket, darray, numverts);
	m_Polygons.push_back(poly);

	return poly;
}
void RAS_MeshObject::AddVertex(RAS_Polygon *poly, int i,
								const MT_Point3& xyz,
								const MT_Point2& uv,
								const MT_Point2& uv2,
								const MT_Vector4& tangent,
								const unsigned int rgba,
								const MT_Vector3& normal,
								bool flat,
								int origindex)
{
	RAS_TexVert texvert(xyz, uv, uv2, tangent, rgba, normal, flat, origindex);
	RAS_MeshMaterial *mmat;
	RAS_DisplayArray *darray;
	RAS_MeshSlot *slot;
	int offset;
	
	mmat = GetMeshMaterial(poly->GetMaterial()->GetPolyMaterial());
	slot = mmat->m_baseslot;
	darray = slot->CurrentDisplayArray();

	{ /* Shared Vertex! */
		/* find vertices shared between faces, with the restriction
		 * that they exist in the same display array, and have the
		 * same uv coordinate etc */
		vector<SharedVertex>& sharedmap = m_sharedvertex_map[origindex];
		vector<SharedVertex>::iterator it;

		for (it = sharedmap.begin(); it != sharedmap.end(); it++)
		{
			if (it->m_darray != darray)
				continue;
			if (!it->m_darray->m_vertex[it->m_offset].closeTo(&texvert))
				continue;

			/* found one, add it and we're done */
			if (poly->IsVisible())
				slot->AddPolygonVertex(it->m_offset);
			poly->SetVertexOffset(i, it->m_offset);
			return;
		}
	}

	/* no shared vertex found, add a new one */
	offset = slot->AddVertex(texvert);
	if (poly->IsVisible())
		slot->AddPolygonVertex(offset);
	poly->SetVertexOffset(i, offset);

	{ /* Shared Vertex! */
		SharedVertex shared;
		shared.m_darray = darray;
		shared.m_offset = offset;
		m_sharedvertex_map[origindex].push_back(shared);
	}
}