mesh.cpp 16.7 KB
Newer Older
1 2
#include "mesh.h"

3
Mesh::SubdivEntry::SubdivEntry()
4
{
5
    VB_handle = 0xFFFFFFFF;
6 7
    IB_irregular_handle = 0xFFFFFFFF;
    IB_regular_handle = 0xFFFFFFFF;
8 9
}

10 11
Mesh::SubdivEntry::~SubdivEntry()
{
12 13
    qDebug()<<"FIXME: Delete Called: num vertex:"<<vertices.size();
    /*f->glDeleteBuffers(1, &VB_handle);
14 15
    f->glDeleteBuffers(1, &IB_irregular_handle);
    f->glDeleteBuffers(1, &IB_regular_handle);
16
    */
17
}
Kai Westerkamp committed
18

19
void Mesh::SubdivEntry::updateIndices() {
20 21 22 23 24 25 26 27 28
    f->glDeleteBuffers(1, &IB_irregular_handle);
    f->glGenBuffers(1, &IB_irregular_handle);
    f->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IB_irregular_handle);
    f->glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * indices_irregular.size(), &indices_irregular[0], GL_STATIC_DRAW);

    f->glDeleteBuffers(1, &IB_regular_handle);
    f->glGenBuffers(1, &IB_regular_handle);
    f->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IB_regular_handle);
    f->glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * indices_regular.size(), &indices_regular[0], GL_STATIC_DRAW);
29 30
}

31
void Mesh::SubdivEntry::init(QOpenGLFunctions_4_3_Core *f,QVector<Vertex>& Vertices,
32
                           QVector<unsigned int>& Indices_irregular){
33 34 35 36 37

    f->glGenBuffers(1, &VB_handle);
    f->glBindBuffer(GL_ARRAY_BUFFER, VB_handle);
    f->glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * Vertices.size(), &Vertices[0], GL_STATIC_DRAW);

38 39
    QVector<unsigned int> patches;
    this->init(f, VB_handle, Vertices, Indices_irregular, patches);
40 41
}

42 43
void Mesh::SubdivEntry::init(QOpenGLFunctions_4_3_Core *f, GLuint VB_handle, QVector<Vertex>& Vertices,
                           QVector<unsigned int>& Indices_irregular, QVector<unsigned int>& patches){
44 45
    this->f = f;
    this->VB_handle = VB_handle;
46

47
    vertices = Vertices;
48 49
    indices_irregular = Indices_irregular;
    indices_regular = patches;
50 51

    qDebug() << "Vertices" << vertices.length();
52
    qDebug() << "Indices irregular" << indices_irregular.length();
53 54
    qDebug() << "Indices patches" << patches.length();

55 56 57
    f->glGenBuffers(1, &IB_irregular_handle);
    f->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IB_irregular_handle);
    f->glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * indices_irregular.size(), &indices_irregular[0], GL_STATIC_DRAW);
58

59 60
    f->glGenBuffers(1, &IB_regular_handle);
    f->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IB_regular_handle);
61
    f->glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * patches.size(), &patches[0], GL_STATIC_DRAW);
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
}


Mesh::MeshEntry::MeshEntry()
{
    materialIndex = 0xFFFFFFFF;
    double amax = std::numeric_limits<float>::max();
    min = QVector3D(amax,amax,amax);
    max = QVector3D(-amax,-amax,-amax);
}

void Mesh::MeshEntry::init(QOpenGLFunctions_4_3_Core *f,QVector<Vertex>& Vertices,
                           QVector<unsigned int>& Indices){
    this->f = f;

    buffers.resize(1);
78 79
    buffers[0].reset(new SubdivEntry);
    buffers[0]->init(f,Vertices,Indices);
80

81 82 83 84 85 86 87 88 89 90 91 92 93
    //calc AABB
    for (int i = 0; i < Vertices.size(); ++i) {
        Vertex v = Vertices[i];
        min.setX(qMin(min.x(),v.pos.x()));
        min.setY(qMin(min.y(),v.pos.y()));
        min.setZ(qMin(min.z(),v.pos.z()));

        max.setX(qMax(max.x(),v.pos.x()));
        max.setY(qMax(max.y(),v.pos.y()));
        max.setZ(qMax(max.z(),v.pos.z()));
    }
}

94
void Mesh::MeshEntry::update(GLuint VB_handle, QVector<Vertex>& Vertices, QVector<unsigned int>& Indices_irregular, QVector<unsigned int>& patches) {
95 96
    SubdivEntry *entry = new SubdivEntry;
    buffers.push_back(std::shared_ptr<SubdivEntry>(entry));
97
    entry->init(f, VB_handle, Vertices, Indices_irregular, patches);
Kai Westerkamp committed
98
}
Kai Westerkamp committed
99

100 101
Mesh::MeshEntry::~MeshEntry()
{
102
    //moved to subdiventry
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
}

Mesh::MaterialInfo::MaterialInfo()
{
    Name = QString("Default");
    Diffuse = QVector3D();
    Specular= QVector3D();
    hasTexture = false;
    texture = Texture();
    Shininess = 30;
}

Mesh::Node::Node()
{
    name = QString("DefaultNode");
    transformation.setToIdentity();
    meshes.clear();
    children.clear();
}

123 124 125 126 127 128 129 130 131 132 133 134 135
bool Mesh::Node::getFirstMeshIndex(int &index){
    if (meshes.length()>0){
        index = meshes[0];
        return true;
    }
    for (int i = 0; i < children.length(); i++){
        if (children[i].getFirstMeshIndex(index)){
            return true;
        }
    }
    return false;
}

136 137 138 139
Mesh::Mesh(QOpenGLFunctions_4_3_Core *f,QString fileName)
{
    loaded = false;
    this->f =f;
Kai Westerkamp committed
140

141 142 143 144 145 146 147
    scene = NULL;
    scene= importer.ReadFile(fileName.toStdString(),
                             //aiProcess_CalcTangentSpace |
                             aiProcess_GenSmoothNormals |
                             //aiProcess_JoinIdenticalVertices |
                             //aiProcess_SortByPType |
                             // ? aiProcess_FlipUVs |
Kai Westerkamp committed
148
                             aiProcess_JoinIdenticalVertices  |
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
                             aiProcess_Triangulate
                             );

    qDebug()<<"File Read";
    if( !scene)
    {
        qDebug()<<importer.GetErrorString();
    }else {
        QString dir = QFileInfo(fileName).path();

        //Init Materials
        materials.resize(scene->mNumMaterials);
        if(scene->HasMaterials()){
            //Init Materials
            for (unsigned int i = 0 ; i < scene->mNumMaterials ; i++) {
                const aiMaterial* material = scene->mMaterials[i];
                aiString mname;
                material->Get(AI_MATKEY_NAME, mname);
                initMaterial(dir, i, material);

                qDebug()<<"Loaded Material"<<(i+1)<<"/"<<scene->mNumMaterials<<":"<<mname.C_Str()<<"Shininess"<<materials[i].Shininess;
            }
        }
        qDebug()<<"Materials Read";

        //Init Mesh
        if(scene->HasMeshes())
        {
            entries.resize(scene->mNumMeshes);
            for (int i = 0 ; i < entries.size() ; i++) {
                aiMesh* meshEntry = scene->mMeshes[i];
                initMeshEntry(i, meshEntry);

            }
        } else{
            qWarning()<<"No Mesh found";
            return;
        }

        qDebug()<<"Mesh Read";

        //init Nodes
        if(scene->mRootNode != NULL)
        {
            initNode(scene, scene->mRootNode, rootNode, QString());
        } else {
            rootNode.transformation.setToIdentity();
            rootNode.children.resize(0);
            rootNode.meshes.resize(entries.length());

            for(int i = 0; i < entries.length(); ++i)
            {
                rootNode.meshes[i] = i;
            }
            qDebug()<<"No Root Node";
        }
        qDebug()<<"Nodes Read";

        globalInverseTransform = rootNode.transformation.inverted();

        double amax = std::numeric_limits<float>::max();
        QVector3D min = QVector3D(amax,amax,amax);
        QVector3D max = QVector3D(-amax,-amax,-amax);

        findObjectDimension(rootNode,QMatrix4x4(),min,max);
        qDebug()<<"AABB"<<min<<max;

        float dist = qMax(max.x() - min.x(), qMax(max.y()-min.y(), max.z() - min.z()));
        float sc = 100.0/dist;
        QVector3D center = (max - min)/2;
        QVector3D trans = -(max - center);

        // Apply the scale and translation to a matrix
        screenTransform.setToIdentity();
        screenTransform.scale(sc);
        screenTransform.translate(trans);

        loaded = true;
    }
}

230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
Mesh::Mesh(QOpenGLFunctions_4_3_Core *f, Mesh *mesh, QVector<Vertex> &vertex_buffer, QVector<GLuint> &index_buffer)
{
    loaded = false;
    this->f = mesh->f;

    scene = mesh->scene;

    //Init Materials
    for (int i = 0; i < mesh->materials.size(); i++) {
        materials.push_back(mesh->materials[i]);
    }

    entries.resize(1);
    entries[0].name = mesh->entries[0].name;
    entries[0].materialIndex = mesh->entries[0].materialIndex;
    entries[0].init(f, vertex_buffer, index_buffer);

    rootNode.name = mesh->rootNode.name;
    rootNode.transformation = mesh->rootNode.transformation;
    rootNode.meshes.resize(1);
    rootNode.meshes[0] = 0;

    globalInverseTransform = rootNode.transformation.inverted();

    double amax = std::numeric_limits<float>::max();
    QVector3D min = QVector3D(amax,amax,amax);
    QVector3D max = QVector3D(-amax,-amax,-amax);

    findObjectDimension(rootNode,QMatrix4x4(),min,max);
    qDebug()<<"AABB"<<min<<max;

    float dist = qMax(max.x() - min.x(), qMax(max.y()-min.y(), max.z() - min.z()));
    float sc = 100.0/dist;
    QVector3D center = (max - min)/2;
    QVector3D trans = -(max - center);

    // Apply the scale and translation to a matrix
    screenTransform.setToIdentity();
    screenTransform.scale(sc);
    screenTransform.translate(trans);

    loaded = true;
}

274 275 276 277 278 279
Mesh::~Mesh()
{
    entries.clear();
    materials.clear();
}

280 281 282 283
Mesh::Node Mesh::getRootNode(){
    return rootNode;
}

284 285
Mesh::MeshEntry *Mesh::getMeshEntry(int index){
    return &entries[index];
286 287
}

288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
void Mesh::initNode(const aiScene *scene, aiNode *node, Node &newNode,QString debugoffset){
    newNode.name = node->mName.length != 0 ? node->mName.C_Str() : "";
    newNode.transformation = QMatrix4x4(node->mTransformation[0]);

    newNode.meshes.resize(node->mNumMeshes);
    if(debug) qDebug()<<debugoffset.toStdString().c_str() << "NodeName" << newNode.name;
    if(debug) qDebug()<<debugoffset.toStdString().c_str() << "  NumMeshes" << newNode.meshes.size();

    for(uint i = 0; i < node->mNumMeshes; ++i)
    {
        newNode.meshes[i] = node->mMeshes[i];
        if(debug) qDebug()<<debugoffset.toStdString().c_str() << "    MeshName" << entries[newNode.meshes[i]].name;
    }

    if(debug) qDebug()<<debugoffset.toStdString().c_str() << "  NumChildren" << node->mNumChildren;
    QString newDebug = QString(debugoffset).append("    ");
    for(uint i = 0; i < node->mNumChildren; ++i)
    {
        newNode.children.push_back(Node());
        initNode(scene, node->mChildren[i], newNode.children[i],newDebug);
    }
}

void Mesh::initMaterial(QString dir, unsigned int i, const aiMaterial* material)
{
    aiString mname;
    material->Get(AI_MATKEY_NAME, mname);
    if (mname.length > 0)
        materials[i].Name = QString(mname.C_Str());

    aiColor3D dif(0.f,0.f,0.f);
    aiColor3D amb(0.f,0.f,0.f);
    aiColor3D spec(0.f,0.f,0.f);
    float shine = 0.0;

    material->Get(AI_MATKEY_COLOR_AMBIENT, amb);
    material->Get(AI_MATKEY_COLOR_DIFFUSE, dif);
    material->Get(AI_MATKEY_COLOR_SPECULAR, spec);
    material->Get(AI_MATKEY_SHININESS, shine);

    materials[i].Diffuse = QVector3D(dif.r, dif.g, dif.b);
    materials[i].Specular = QVector3D(spec.r, spec.g, spec.b);
    materials[i].Shininess = shine;

    if (materials[i].Shininess == 0.0){
        materials[i].Shininess = 2;
    }

    if (material->GetTextureCount(aiTextureType_DIFFUSE) > 0) {
        aiString Path;

        if (material->GetTexture(aiTextureType_DIFFUSE, 0, &Path, NULL, NULL, NULL, NULL, NULL) == AI_SUCCESS) {
            QString temp = QString(Path.data);
            temp = temp.split("\\").last();
            temp = temp.split("/").last();
            std::string FullPath = dir.toStdString() + "/" + temp.toStdString();
            materials[i].texture.Load(GL_TEXTURE_2D, QString(FullPath.c_str()));
            materials[i].hasTexture = true;
        } else{
            qDebug()<<"Warning No Texture";
            materials[i].hasTexture = false;
        }
    }
}

353
void Mesh::initMeshEntry(int index, aiMesh * entry) {
354 355 356 357 358
    QVector<Vertex> Vertices;
    QVector<unsigned int> Indices;

    const aiVector3D Zero3D(0.0f, 0.0f, 0.0f);

359
    for (unsigned int i = 0; i < entry->mNumVertices; i++) {
360 361 362 363 364 365 366 367 368 369 370 371 372
        const aiVector3D* pPos      = &(entry->mVertices[i]);
        const aiVector3D* pNormal   = &(entry->mNormals[i]);
        const aiVector3D* pTexCoord = entry->HasTextureCoords(0) ? &(entry->mTextureCoords[0][i]) : &Zero3D;

        //possible: nuuv Channels, TAngents and Bitangents

        Vertex v(QVector3D(pPos->x, pPos->y, pPos->z),
                 QVector3D(pNormal->x, pNormal->y, pNormal->z),
                 QVector2D(pTexCoord->x, pTexCoord->y));

        Vertices.push_back(v);
    }

373
    for (unsigned int i = 0; i < entry->mNumFaces; i++) {
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
        const aiFace& face = entry->mFaces[i];
        assert(face.mNumIndices == 3);
        Indices.push_back(face.mIndices[0]);
        Indices.push_back(face.mIndices[1]);
        Indices.push_back(face.mIndices[2]);
    }

    entries[index].name = entry->mName.length != 0 ? entry->mName.C_Str() : "";
    entries[index].materialIndex = entry->mMaterialIndex;

    qDebug()<<"Loaded Mesh:"<<entries[index].name<<"HasBones:"<<entry->HasBones();

    entries[index].init(f,Vertices, Indices);
}

389
void Mesh::render(QOpenGLShaderProgram *shader, QMatrix4x4 V,QMatrix4x4 P, int subdivision, bool regular){
390 391 392
    if(!loaded)
        return;
    if(f == NULL){
Kai Westerkamp committed
393
        qDebug()<<"OpenGL Funktions = null";
394 395 396 397 398 399 400
        return;
    }

    f->glEnableVertexAttribArray(positionIndex);
    f->glEnableVertexAttribArray(normalIndex);
    f->glEnableVertexAttribArray(uvIndex);

401
    renderNode(shader,rootNode,V*screenTransform,P,QMatrix4x4(),subdivision, regular);
402 403 404 405 406 407

    f->glDisableVertexAttribArray(positionIndex);
    f->glDisableVertexAttribArray(normalIndex);
    f->glDisableVertexAttribArray(uvIndex);
}

408
void Mesh::renderNode(QOpenGLShaderProgram *shader, Node &node, QMatrix4x4 V,QMatrix4x4 P,QMatrix4x4 M, int subdivision, bool regular){
409 410 411 412 413 414 415 416 417 418 419
    M *= node.transformation;

    QMatrix4x4 MV = V*M;
    QMatrix4x4 MVP = P*MV;

    shader->setUniformValue("MVP",MVP);
    shader->setUniformValue("MV",MV);

    for (int i = 0 ; i < node.meshes.size() ; i++) {
        int index = node.meshes[i];
        //load Material
420
        renderMesh(shader, index,subdivision, regular);
421 422 423
    }

    for (int i = 0 ; i < node.children.size() ; i++) {
424
        renderNode(shader,node.children[i],V,P,M, subdivision,regular);
425 426 427
    }
}

428
void Mesh::renderMesh(QOpenGLShaderProgram *shader, int index, int subdivision, bool regular)
429 430 431
{
    int MaterialIndex = entries[index].materialIndex;
    if (MaterialIndex < materials.size()) {
Kai Westerkamp committed
432
        // qDebug()<<materials[MaterialIndex].Diffuse<<materials[MaterialIndex].Specular<<materials[MaterialIndex].Shininess<<materials[MaterialIndex].hasTexture;
433

434 435 436 437 438
        if (regular) {
            shader->setUniformValue("materialInfo.Diffuse", QVector3D(0.0f, 0.0f, 1.0f));
        } else {
            shader->setUniformValue("materialInfo.Diffuse", materials[MaterialIndex].Diffuse);
        }
439 440 441 442 443 444 445 446
        shader->setUniformValue("materialInfo.Specular",materials[MaterialIndex].Specular);
        shader->setUniformValue("materialInfo.Shininess",materials[MaterialIndex].Shininess);
        shader->setUniformValue("materialInfo.hasTexture",materials[MaterialIndex].hasTexture);

        if(materials[MaterialIndex].hasTexture)
            materials[MaterialIndex].texture.bind(f,GL_TEXTURE0);
    }

447
    if(entries[index].buffers.size() <= subdivision){
448 449 450
        subdivision = entries[index].buffers.size()-1;
    }

451
    std::shared_ptr<SubdivEntry> entry = entries[index].buffers[subdivision];
452 453 454

    // Draw Vertex Array

455
   // qDebug()<<"Render"<<subdivision<<entry->indices_irregular;
456 457

    if(regular){
458
        if (!entry->indices_regular.isEmpty()) {
459 460
            f->glBindBuffer(GL_ARRAY_BUFFER, entry->VB_handle);
            f->glVertexAttribPointer(positionIndex, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);
461

462
            f->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, entry->IB_regular_handle);
463
            f->glPatchParameteri(GL_PATCH_VERTICES, 12);
464
            f->glDrawElements(GL_PATCHES, entry->indices_regular.size(), GL_UNSIGNED_INT, 0);
465 466
        }
    } else {
467
        if (!entry->indices_irregular.isEmpty()) {
468 469 470
            f->glBindBuffer(GL_ARRAY_BUFFER, entry->VB_handle);
            f->glVertexAttribPointer(positionIndex, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);

471
            f->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, entry->IB_irregular_handle);
472
            f->glPatchParameteri(GL_PATCH_VERTICES, 3);
473
            f->glDrawElements(GL_PATCHES, entry->indices_irregular.size(), GL_UNSIGNED_INT, 0);
474
        }
475
    }
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
}

void Mesh::findObjectDimension(Node node, QMatrix4x4 transform, QVector3D &min, QVector3D &max){
    transform *= node.transformation;

    for (int i = 0; i < node.meshes.size(); i++) {
        QVector4D temp = transform*QVector4D(entries[node.meshes[i]].min,1.0);
        min.setX(qMin(min.x(),temp.x()));
        min.setY(qMin(min.y(),temp.y()));
        min.setZ(qMin(min.z(),temp.z()));
        max.setX(qMax(max.x(),temp.x()));
        max.setY(qMax(max.y(),temp.y()));
        max.setZ(qMax(max.z(),temp.z()));

        temp = transform*QVector4D(entries[node.meshes[i]].max,1.0);
        min.setX(qMin(min.x(),temp.x()));
        min.setY(qMin(min.y(),temp.y()));
        min.setZ(qMin(min.z(),temp.z()));
        max.setX(qMax(max.x(),temp.x()));
        max.setY(qMax(max.y(),temp.y()));
        max.setZ(qMax(max.z(),temp.z()));
    }

    for (int i = 0; i < node.children.size(); i++) {
        findObjectDimension(node.children[i], transform, min, max);
    }
}