geometry-central icon indicating copy to clipboard operation
geometry-central copied to clipboard

Binary STL reader seek to file begin

Open mgsutton opened this issue 4 years ago • 2 comments

In the function SimplePolygonMesh::readMeshFromBinaryStlFile(std::istream& in) we need to seek back to the beginning of the file before processing the 80 byte header and triangle count. In the calling function, the stream is examined to see if the first line contains the token "solid", which flags the file as an ASCII STL file. However, once we determine that the file represents a binary STL, the current stream position is at the end of the first "delimited line" in the file. So, inserting a in.seekg(0, in.beg); before the header read fixes the issue.

mgsutton avatar Jan 02 '21 20:01 mgsutton

Hi, thanks for raising this!

I think I understand the issue. I guess the current method gets lucky and only sometimes works when the data in the 80 char binary header causes the stringstream to read nothing.

However, one question about your proposed fix---I worry that if this parser is reading the file from a long stream containing lots of data (e.g. many serialized objects), seeking all the way to the beginning might be an issue.

What about instead doing something like

char tokenChar[16];
in.read(tokenChar, 5);
if(tokenChar == "solid") {
  // parse ascii
} else {
  // rewind (undo the seek)
  in.seekg(-5, std::ios::cur)
  // parse binary
}

to just rewind the stream as far as the "token" characters we looked for? Does that sound reasonable?

nmwsharp avatar Jan 04 '21 17:01 nmwsharp

Yes. I think that is probably safer in general. Honestly, I was a little uneasy about just trying to read a "line" in a file that contains binary STL data, but just settled for a quick fix. So, your approach seems much safer in general. I'll try it on my end to make sure there are no hidden issues. i.e. it might be better to compare case insensitive to "solid", and I don't know if its worth filling the tokenChar buffer with zeros to make sure we have a delimiter in there. BTW, really appreciate the library!

mgsutton avatar Jan 04 '21 17:01 mgsutton

Are we able to close this issue?

NewWheelTech avatar Sep 20 '23 15:09 NewWheelTech

I would think so.

mgsutton avatar Sep 22 '23 13:09 mgsutton