我正在尝试为 DirectX 引擎编写模型文件加载器...
目前看起来是这样的:
irrFireMesh* irrFireDevice::loadModel(char* filename)
{
ifstream in_stream;
string line;
in_stream.open(filename);
int vertexCount = 0;
int vCount = -1;
irrFireMesh* triangleMesh = new irrFireMesh();
irrFireVertex* vertices;
unsigned long* indices;
irrFireMaterial* mat;
while(getline(in_stream, line, '\n'))
{
std::string word;
std::stringstream stream(line);
std::string param[15];
int i = 0;
while( getline(stream, word, ' ') ){
param[i] = word;
i++;
}
then = timeGetTime();
if(param[0] == "newbuf")
{
vertexCount = StI(param[1]);
vertices = new irrFireVertex[vertexCount];
if(!vertices) return NULL;
indices = new unsigned long[vertexCount];
if(!indices) return NULL;
mat = new irrFireMaterial(this);
cout<<"Begin buffer width "<<vertexCount<<" vertices"<<endl;
vCount = -1;
continue;
}
if(vertexCount <= 0) continue;
if(param[0] == "endbuf")
{
irrFireMeshBuffer* mbuf = new irrFireMeshBuffer();
mbuf->vertexCount = vertexCount;
mbuf->indexCount = vertexCount;
mbuf->vertices = vertices;
mbuf->indices = indices;
mat->INITIALIZE();
mbuf->material = mat;
triangleMesh->addMeshBuffer(mbuf);
vertexCount = 0;
cout<<"End buffer width "<<vCount+1<<" vertices."<<endl;
continue;
}
if(param[0] == "v")
{
vCount++;
vertices[vCount].position = D3DXVECTOR3(StF(param[1]), StF(param[3]), StF(param[2]));
vertices[vCount].color = D3DXVECTOR4(1.0f, 1.0f, 1.0f, 1.0f);
vertices[vCount].uv = D3DXVECTOR2((StF(param[1]) + StF(param[3]))*10.0f, StF(param[2])*10.0f);
indices[vCount] = vCount;
if((vCount+1) % 3 == 0)
{
D3DXVECTOR3 NRML, D1, D2;
D1 = vertices[vCount-2].position - vertices[vCount-1].position;
D2 = vertices[vCount-1].position - vertices[vCount].position;
D3DXVec3Cross(&NRML, &D1, &D2);
D3DXVec3Normalize(&NRML, &NRML);
vertices[vCount-2].normal = NRML;
vertices[vCount-1].normal = NRML;
vertices[vCount].normal = NRML;
}
continue;
}
}
in_stream.close();
return triangleMesh;
}
三角形的模型文件如下所示:
newbuf 3
v 0.0 0.0 0.0
v 0.5 1.0 0.0
v 1.0 0.0 0.0
endbuf
加载复杂模型时,它按预期工作,但是太慢了...您能否向我指出瓶颈并指出解决此问题的更快方法?
编辑:好的,我对某些函数所需的时间进行了基准测试,结果证明,解析部分
if(param[0] == "v")
{
.
.
.
}
解析 23400 个顶点时,总共需要大约 4000 毫秒。但是当我更换
vertices[vCount].position = D3DXVECTOR3(StF(param[1]), StF(param[3]), StF(param[2]));
和
vertices[vCount].position = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
总共只需要大约 300 毫秒。所以性能杀手似乎是 StF() 看起来像这样:
float StF(string in)
{
stringstream mystr("");
mystr<<in;
float res = 0;
mystr>>res;
return res;
}
任何想法,如何做对?因为这显然太慢了……