#include "mesh.h"

Mesh::Mesh(std::string Name)
{
    this->Name = Name;
}

Mesh::~Mesh()
{
    for(std::vector<Face*>::iterator i = faces.begin(); i != faces.end(); i++)
        delete *i;
    for(std::vector<Point3D*>::iterator i = points.begin(); i != points.end(); i++)
        delete *i;
}

void Mesh::ExportToBlender(std::ostream &os)
{
    std::map<Point3D*, int> VertIndex;
    int NextIndex = 0;

    // write python-script for creation of vertices
    os << "vertices = (";
    std::string glue = "";
    for(std::vector<Point3D*>::iterator p = points.begin(); p != points.end(); p++)
    {
        VertIndex[*p] = NextIndex++;
        os << glue << "(" << ((*p)->x * 0.01) << "," << ((*p)->z * 0.01) << "," << ((*p)->y * -0.01) << ")";
        os.flush();
        glue = ",\n            ";
    }
    os << ")\n\n";
    os.flush();

    // write python-script for creation of faces
    os << "faces = (";
    os.flush();
    glue = "";
    for(std::vector<Face*>::iterator f = faces.begin(); f != faces.end(); f++)
    {
        os << glue << "(";
        glue = ",\n         ";

        std::string glue2 = "";
        for(std::vector<Point3D*>::iterator p = (*f)->verts.begin(); p != (*f)->verts.end(); p++)
        {
            os << glue2 << VertIndex[*p];
            glue2 = ",";
        }
        os << ")";
    }
    os << ")\n\n";

    os << "mesh = bpy.data.meshes.new('" << Name << "_Mesh')\n";
    os << "mesh.from_pydata(vertices, [], faces)\n";
    os << "object = bpy.data.objects.new('" << Name << "', mesh)\n";
    os << "bpy.context.scene.objects.link(object)\n\n";
}
