#include <amscudafractallevelset/amscudafractallevelset.cuh>

namespace amscuda
{
namespace fractallevelset
{

    bagoftriangles::bagoftriangles()
    {
        vertices.resize(0);
        return;
    }

    bagoftriangles::~bagoftriangles()
    {
        vertices.resize(0);
        return;
    }

    static triangle _local_get_tri(float *data, int index)
    {
        triangle ret;
        ret.p0 = cuvec3f(data[index+0],data[index+1],data[index+2]);
        ret.p1 = cuvec3f(data[index+3],data[index+4],data[index+5]);
        ret.p2 = cuvec3f(data[index+6],data[index+7],data[index+8]);
        return ret;
    }

    int bagoftriangles::save_stl(const char *fname)
    {
        int ret = 0;
        FILE *fp = NULL;
        long N,I;
        triangle tri;
        cuvec3f normal;

        fp = fopen(fname,"w+");
        if(fp==NULL)
        {
            ret = -1;
            return ret;
        }

        //write header
        fprintf(fp,"solid levelset\n");
        N = vertices.length/9;
        for(I=0;I<N;I++)
        {
            tri = _local_get_tri(vertices.data,I*9);
            normal = tri.normal();
            fprintf(fp,"facet normal %1.6g %1.6g %1.6g\n",normal[0],normal[1],normal[2]);
            fprintf(fp,"\touter loop\n");
            fprintf(fp,"\t\tvertex %1.6g %1.6g %1.6g\n",tri.p0[0],tri.p0[1],tri.p0[2]);
            fprintf(fp,"\t\tvertex %1.6g %1.6g %1.6g\n",tri.p1[0],tri.p1[1],tri.p1[2]);
            fprintf(fp,"\t\tvertex %1.6g %1.6g %1.6g\n",tri.p2[0],tri.p2[1],tri.p2[2]);
            fprintf(fp,"\tendloop\n");
            fprintf(fp,"endfacet\n");
        }

        fprintf(fp,"endsolid levelset\n");


        fclose(fp);
        ret = 1;
        return ret;
    }


    
};//end namespace fractallevelset
};// end namespace amscuda
