Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing binary .stl files in C++

Tags:

c++

fstream

I want to write data from an vector of coordinates into a binary .stl 3d geometry file.

I need to have a 80 bit header, 24bit number of triangles. Each triangle is supposed to be defined by 3 points and one normal, each of which coordinate values is 32 bit.In addition, each triangle may have an attribute, which I wanted to leave empty. (See wiki )

I guess I am still having misunderstanding about char and binary mode.

The file that is produced in the end has the same size as my original file but cannot be read by the graphics programme, so there needs to be a logical mistake still...

My point coordinates are double valued before casting to char*, is this ok to do so??

line out of the binary file

My code:

void write_stl(std::string filename, std::vector<tri> triangles){

    //binary file
    std::string header_info = "solid " + filename + "-output";
    char head[80];
    std::strncpy(head,header_info.c_str(),sizeof(head)-1);
    char attribute[2] = "0";
    unsigned long nTriLong = triangles.size() ;

    std::ofstream myfile;

    myfile.open((Filename + "-out.stl").c_str(),  std::ios::out | std::ios::binary);
    myfile.write(head,sizeof(head));
    myfile.write((char*)&nTriLong,4);

    //write down every triangle
    for (std::vector<tri>::iterator it = triangles.begin(); it!=triangles.end(); it++){
        //normal vector coordinates

        myfile.write((char*)&it->m_n.m_x, 4);
        myfile.write((char*)&it->m_n.m_y, 4);
        myfile.write((char*)&it->m_n.m_z, 4);

        //p1 coordinates
        myfile.write((char*)&it->m_p1.m_x, 4);
        myfile.write((char*)&it->m_p1.m_y, 4);
        myfile.write((char*)&it->m_p1.m_z, 4);

        //p2 coordinates
        myfile.write((char*)&it->m_p2.m_x, 4);
        myfile.write((char*)&it->m_p2.m_y, 4);
        myfile.write((char*)&it->m_p2.m_z, 4);

        //p3 coordinates
        myfile.write((char*)&it->m_p3.m_x, 4);
        myfile.write((char*)&it->m_p3.m_y, 4);
        myfile.write((char*)&it->m_p3.m_z, 4);

        myfile.write(attribute,2);
    }

    myfile.close();
}

Where tri is just a structure for a triangle containing the 3 points and the normal as "3D vectors" (i.e. Structures with x,y,z, value) ...

like image 938
Rea Avatar asked Oct 15 '25 05:10

Rea


1 Answers

The size argument to write() is the size in bytes, not in bits. You are passing 32 for a float when you should be passing 4.

like image 109
mattnewport Avatar answered Oct 17 '25 20:10

mattnewport



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!