1

Нашел код, который работает более тесно с OpenGL из Qt3D. Он отрисовывал линию, но я его немнго поменял, чтобы он рисовал треугольники. Когда я устанавливаю setPrimitiveType(Qt3DRender::QGeometryRenderer::TriangleStrip);, то он прекрасно отрисовывает. Но это не то, что мне нужно. Когда я ставлю нужный мне setPrimitiveType(Qt3DRender::QGeometryRenderer::Triangles);, то не отрисовывается ничего. Может, я неправильные данные в него направляю или не правильно его настроил? (Пример данных внизу)

void MainWindow::drawTriangles(const QPolygonF polygon, QColor color, Qt3DCore::QEntity *_rootEntity)
{
    int numOfVertices = polygon.size();
    auto *geometry = new Qt3DRender::QGeometry(_rootEntity);

    // Создаем и заполняем вершинный буфер
    QByteArray bufferBytes;
    bufferBytes.resize(3 * numOfVertices * static_cast<int>(sizeof(float)));
    float *positions = reinterpret_cast<float*>(bufferBytes.data());

    for(auto point : polygon){
        float fHalfMapWidth = (dFittedMaxMapX_ - dFittedMinMapX_) / 2;
        float fHalfMapHeight = (dFittedMaxMapY_ - dFittedMinMapY_) / 2;

        *positions++ = static_cast<float>(point.x() - (dFittedMinMapX_ + fHalfMapWidth));
        *positions++ = 0.0f; //We need to drow only on the surface
        *positions++ = static_cast<float>(point.y() - (dFittedMinMapY_ + fHalfMapHeight));
    }

    auto *buf = new Qt3DRender::QBuffer(geometry);
    buf->setData(bufferBytes);

    auto *positionAttribute = new Qt3DRender::QAttribute(geometry); // Создаем вертексный атрибут
    positionAttribute->setName(Qt3DRender::QAttribute::defaultPositionAttributeName());
    positionAttribute->setVertexBaseType(Qt3DRender::QAttribute::Float); //В буфере у нас будут флоаты
    positionAttribute->setVertexSize(3); // Размер одной вершины
    positionAttribute->setAttributeType(Qt3DRender::QAttribute::VertexAttribute); // Тип атрибута
    positionAttribute->setBuffer(buf); // Сам буфер
    positionAttribute->setByteStride(3 * sizeof(float)); // Шаг между вершинами
    geometry->addAttribute(positionAttribute); // Добавляем атрибут в наш Qt3DRender::QGeometry

    // Создаем и заполняем индексный буфер
    QByteArray indexBytes;
    indexBytes.resize(numOfVertices * static_cast<int>(sizeof(unsigned int))); // start to end
    unsigned int *indices = reinterpret_cast<unsigned int*>(indexBytes.data());
    for(unsigned int i = 0; i < static_cast<unsigned int>(numOfVertices); ++i) {
        *indices++ = i;
    }

    auto *indexBuffer = new Qt3DRender::QBuffer(geometry);
    indexBuffer->setData(indexBytes);

    auto *indexAttribute = new Qt3DRender::QAttribute(geometry); // Создаем индексный атрибут
    indexAttribute->setVertexBaseType(Qt3DRender::QAttribute::UnsignedInt); // Тип данных в индексном буфере
    indexAttribute->setAttributeType(Qt3DRender::QAttribute::IndexAttribute); // Тип атрибута
    indexAttribute->setBuffer(indexBuffer); // Сам индексный буфер
    indexAttribute->setCount(static_cast<unsigned int>(numOfVertices)); // Количество вершин, как я понял
    geometry->addAttribute(indexAttribute); // Добавляем атрибут в наш Qt3DRender::QGeometry


    auto *poly = new Qt3DRender::QGeometryRenderer(_rootEntity);
    poly->setGeometry(geometry); // Устанавливаем нашу геометрию
    //poly->setPrimitiveType(Qt3DRender::QGeometryRenderer::TriangleStrip); - Рабочий варииант
    poly->setPrimitiveType(Qt3DRender::QGeometryRenderer::Triangles); // - Почему-то не выводит ничего

    //Создаем материал
    auto *material = new Qt3DExtras::QPhongMaterial(_rootEntity);
    material->setAmbient(color);

    auto *trianglesEntity = new Qt3DCore::QEntity(_rootEntity);
    trianglesEntity->addComponent(poly); // Добавляем наш рисунок
    trianglesEntity->addComponent(material); // Добавляем наш материал
}

Пробовал и три точки и четыре. С четырьмя получается только с TriangleStrip. С Triangles не получается в обоих случаях.

mapBorder << QPointF(300,200) << QPointF(100,200) << QPointF(200,0) << QPointF(300,200) << QPointF(200,0) << QPointF(500,200) << QPointF(500,300); 
drawTriangles(mapBorder, QColor(Qt::black), mapEntity_);

1 ответ 1

1

На английском стаковерфлоу подсказали. Для треугольника необходимо и достаточно только 3 вершины. У меня не было отрисовки в режиме Triangles, потому что по-умолчанию отрисовка примитивов происходит по часовой стрелки, а я давал на вход вершины в обратном порядке. Если изменить их порядок на "по часовой стрелке", то все начинает отрисовываться. Чтобы изменить это поведение на отрисовку обратного порядка или для отрисовки обоих порядков можно использовать https://doc.qt.io/qt-5.11/qt3drender-qcullface.html#details Я до конца не понимаю, как это правильно указывать, но сделал кривую реализацию, основываясь на коде из ответа отсюда https://stackoverflow.com/questions/51818584/2d-meshes-in-qt3d

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.