Java read md2_triangle_t

Started by
1 comment, last by polyfrag 11 years, 1 month ago

I'm trying to load an .md2 model in Java.

There's a structure like this:


struct md2_triangle_t 
{ 
    unsigned short vertex[3]; 
    unsigned short st[3]; 
};

Will there be byte packing? Where and how many bytes do I skip? Or can I read the 2-byte unsigned shorts one after the other?

Advertisement

Take a look at the DataInputStream, there are methods to read ushorts etc. Padding etc. are often memory/compiler options, I would think, that the above structure is written 1:1, therefor try something like this:


// fast pseudo code, needs some checking and cleaning up 
class md2_triangle_t 
{
  public int vertex[3];
  public int st[3];


public void readFromStream(DataInputStream _inputStream)
 {
vertex[0] = _inputStream.readUnsignedShort();
vertex[1] = _inputStream.readUnsignedShort();
vertex[2] = _inputStream.readUnsignedShort();

st[0] = _inputStream.readUnsignedShort();
st[1] = _inputStream.readUnsignedShort();
st[2] = _inputStream.readUnsignedShort();
}

}

They're little-endian ushorts so


        // http://darksleep.com/player/JavaAndUnsignedTypes.html
	static char ReadUShort(InputStream iS, int offset)
	{
		byte[] bucket = ReadBytes(iS, offset, 2);
                // switched bytes for little-endian:
                int firstByte = (0x000000FF & ((int)bucket[1]));
                int secondByte = (0x000000FF & ((int)bucket[0]));
                return (char) (firstByte << 8 | secondByte);
	}


        static byte[] ReadBytes(InputStream iS, int offset, int readlen)
        {
                byte[] bucket = new byte[offset+readlen];
        
                try 
                {
                        iS.read(bucket, offset, readlen);
                } 
                catch (IOException e) 
                {
                        e.printStackTrace();
                }

                byte subbucket[] = new byte[readlen];

                for(int i=0; i<readlen; i++)
                        subbucket = bucket[offset+i];
        
                return subbucket;
        }

This topic is closed to new replies.

Advertisement