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??
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" (ie Structures with x,y,z, value) ...
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.