Rajawali 教程04优化

本文介绍如何优化加载大型OBJ模型,并通过序列化避免每次加载相同文件,从而提升性能。同时,实现批处理几何图形共享材质与结构,减少CPU和GPU间调用次数,提高效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过优化,可以加载大型OBJ模型;通过序列化可避免每次都去加载一个.obj文件;它主要写所有相关的数据(顶点、指数正常,纹理坐标和颜色)二进制文件在磁盘上。

因此.obj文件必须在开发过程中只加载一次。一旦文件加载您可以将其保存到sdcard。为了做到这一点,首先需要在Androidmanifest.xml 配置写入权限。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
如果你支持Android 4.2.2还需要:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
加载并序列化一个文件:

MeshExporter exporter = new MeshExporter(myBaseObject3D);
exporter.export("myBaseObject3Dname", ExportType.SERIALIZED);
当这段代码完成.obj文件可以被丢弃,序列化文件写入到sd卡,被复制到资源文件夹(res/raw)

序列化模型现在已经准备好被加载到您的应用程序:

try {
	ObjectInputStream ois;
	ois = new ObjectInputStream(mContext.getResources().openRawResource(R.raw.my_serialized_model));
	mMyModel = new BaseObject3D((SerializedObject3D)ois.readObject());
	addChild(mMyModel);
	ois.close();
} catch (Exception e) {
	e.printStackTrace();
}
OK 搞定 进入下一个环节。

批处理几何图形

有时你可以将很多的相同类型的对象共享相同的材料。例如:球体的颜色材料

Appolonian sphere packing example - many identical objects

或多个数据集共享相同的结构:

Lots of cubes sharing a texture

而不是创建一个着色器,上传纹理,顶点缓冲区,等等对于相同的可以使用相同的,这样会使CPU和GPU之间的调用的数量急剧下降。

怎么做?

// -- First create the main object with a material and a texture.
//     The child objects will be cloned from this object.
Cube rootCube = new Cube(1.5f);
rootCube.setMaterial(new DiffuseMaterial());
rootCube.addLight(mLight);
rootCube.addTexture(mTextureManager.addTexture(b));
// -- This line indicates that all children will use the same material,
//     texture, vertices, indices, etc. The children can have their
//     own transformation and color.
rootCube.setRenderChildrenAsBatch(true);
addChild(rootCube);	

for(int i=0; i<500; i++) {
	// -- Clone from the main object and then set a position and rotation.
	BaseObject3D c = rootCube.clone();
	c.setPosition(-25f + (float)(Math.random() * 50f), -25f + (float)(Math.random() * 50f), -25f + (float)(Math.random() * 50f));
	c.setRotation((float)Math.random() * 360, (float)Math.random() * 360, (float)Math.random() * 360);
	rootCube.addChild(c);
}
正如你所看到的每一个对象都可以有它自己的旋转、位置和规模。如果你不使用纹理也可以改变单个对象的颜色。请注意,后者将创建一个新的缓冲可能降低性能(但不明显)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值