做web可视化尤其是三维可视化的肯定都知道glb模型,它是gltf模型的二进制格式,说白了引入glb格式实则是为了解决当gltf文件比较大时的传输和加载问题。

gltf我们在上一篇文章中详细介绍了其格式,尤其是用来存储几何信息、纹理信息以及动画信息的buffer数据,它一般是通过uri指向一个外部文件,列如xxx.bin文件或者是将uri内容通过base64编码嵌入内部,但是无论是哪种情况都需要必定的开销,而且通过base64编码还会增加gltf的文件大小,因此就有了今天的我们要说的glb文件。
glb的组织格式如下:

其中前12个字节是固定位称为头部(header),分别存储如下信息:
1、文件标识(magic),其值必须是0x46546C67这个值实则就是ASCII 字符串 glTF,用来标表明这个是二进制的gltf;
2、版本(version),其值为2表明为gltf的2.0版本。
3、总长度(length),表明glb的总长度,包括header+chunk;
而接下来就是多个块数据,每一个块数据都有固定的结构,包括块长度,块类型和真正的块数据,其中块长度和块类型分别占4个字节,而块数据则是由块长度决定的,但是每个块数据其起始位置和结束位置必须与4字节对齐,列如第一块的起始位置不用说,肯定是对齐的,由于其起始位置就是第12个字节,但是其结束位置chunkData,如果长度不是4的倍数,则需要补充对齐,列如其chunkdata的字节长度为21,则需要在后面补充3个空格,以使得最终的字节数为4的倍数,依次类推,后面的块数据也一样。

对于块数据的类型定义一般有两种,一种是JSON格式必须是0x4E4F534A,另一种是bin格式其值必须是0x004E4942。
基于上述的理论知识,下面小编就使用java语言解析一个glb文件,其它不多说,直接看代码:
public static void main(String[] args) throws IOException {
String glbFile = "D:\data\glb\wx.glb";
//使用RandomAccessFile读取文件
RandomAccessFile randomAccessFile = new RandomAccessFile(glbFile,"rw");
//获取filechannel
FileChannel fileChannel = randomAccessFile.getChannel();
//申请4个字节读取magic
ByteBuffer byteBuffer = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN);
fileChannel.read(byteBuffer);
byte[] bytes = new byte[4];
byteBuffer.flip();
byteBuffer.get(bytes);
String magic = new String(bytes);
System.out.println(magic);
//读取version
byteBuffer.flip();
fileChannel.position(4);
fileChannel.read(byteBuffer);
int version = byteBuffer.flip().getInt();
System.out.println(version);
//读取整个长度
byteBuffer.flip();
fileChannel.position(8);
fileChannel.read(byteBuffer);
int length = byteBuffer.flip().getInt();
System.out.println(length);
//获取第一个chunkdata的length
byteBuffer.flip();
fileChannel.position(12);
fileChannel.read(byteBuffer);
int chunklength1 = byteBuffer.flip().getInt();
System.out.println(chunklength1);
//获取第一个chunktype
byteBuffer.flip();
fileChannel.position(16);
fileChannel.read(byteBuffer);
//如果想转为16进制的0x4E4F534A可以使用下面的代码
// int chunktype1 = byteBuffer.flip().get();
// System.out.println(Integer.toHexString(chunktype1));
byteBuffer.flip().get(bytes);
String chunktype = new String(bytes);
System.out.println(chunktype);
}
而最终的结果也和我们预期的一致,具体如下:

好了,今天关于glb文件格式,以及如何使用java语言解析glb文件给了一个简单的示例。


