qt - 在 QML 中控制带纹理的 3D 对象不透明度

标签 qt opengl qt5 shader qt3d

我对 QML 中的 Qt 3D 有点陌生,我正在尝试控制 的不透明度纹理 3D 对象。
我正在使用 simpleqml3d测试项目才能做到这一点。

我玩过这些 Material ,但无法让它发挥作用。
这是我修改过的 IronMan.qml来自 simpleqml3d 的实体测试项目:

import Qt3D.Core 2.0
import Qt3D.Render 2.0
import Qt3D.Extras 2.0

Entity {
    id: root

    property real x: 0
    property real y: 0
    property real z: 0
    property real scale: 1.0

    Texture2D{
        id: texture
        TextureImage {
            source: "qrc:/man.png"
        }
    }

    //COPY RenderableEntity.qml in your project!!!!!!
    RenderableEntity{
        id: chest
        source: "qrc:/man.obj" //Path to iron man model. You can open it with 3D Builder on Windows 10
        position: Qt.vector3d(root.x, root.y, root.z)
        scale:  root.scale

//        material: DiffuseMapMaterial {
//            id: material
//            diffuse:  texture
//            specular: Qt.rgba( 0.2, 0.2, 0.2, 1.0 )
//            shininess: 2.0
//        }

//        material: DiffuseMapMaterial {
//            diffuse:  texture
//            specular: Qt.rgba( 0.2, 0.2, 0.2, 1.0 )
//            shininess: 2.0
//        }

//        material: DiffuseSpecularMaterial {
//            alphaBlending: true
//            diffuse: Qt.rgba(0.2, 0.2, 0.2, 0.0)//texture
//            specular: texture//Qt.rgba(0.2, 0.2, 0.2, 0.5)
//            shininess: 2.0
//        }

//        material: PhongMaterial {
//            ambient: Qt.rgba( 1, 0, 0, 0 )
//            diffuse: Qt.rgba( 1, 0, 0, 0 )
//            shininess: 50
//        }

//        material: PhongAlphaMaterial {
//            alpha: 0.0
//            diffuse: Qt.rgba(0.2, 0.2, 0.2, 0.0)//texture
//            specular: Qt.rgba(0.2, 0.2, 0.2, 0.0)
//            shininess: 2.0
//        }

        material: PhongAlphaMaterial {
            alpha: 0.0
            ambient: Qt.rgba( 1, 0, 0, 0 )
            diffuse: Qt.rgba( 1, 0, 0, 0 )
            shininess: 50
        }
    }
}

评论的 Material 是我玩过的 Material 。即使没有 PhongAlphaMaterial 我也无法工作, 当不透明度设置为 0.0 时,模型仍然显示如下:

enter image description here

有人可以帮我控制带纹理的 3D 对象不透明度,但又不会丢失纹理吗?

编辑:

我已经接受了 Florian Blume 的答案,因为答案基于 Github 存储库,所以我认为最好将代码也放在 StackOverflow 上,以防他的 fork 存储库分支发生不好的事情。因此,我将在此处发布完全使项目工作的来源。

simpleqml3d.pro
TEMPLATE = app

QT += core gui widgets 3dcore 3drender 3dinput 3dquick qml quick 3dquickextras
CONFIG += c++11

SOURCES += main.cpp

RESOURCES += resources.qrc

# Additional import path used to resolve QML modules in Qt Creator's code model
QML_IMPORT_PATH =

# Additional import path used to resolve QML modules just for Qt Quick Designer
QML_DESIGNER_IMPORT_PATH =

# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

main.cpp
/****************************************************************************
**
** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB).
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt3D module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of The Qt Company Ltd nor the names of its
**     contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <Qt3DQuickExtras/qt3dquickwindow.h>
#include <Qt3DQuick/QQmlAspectEngine>
#include <QGuiApplication>
#include <QQmlEngine>
#include <QQmlContext>

int main(int argc, char* argv[])
{
    QGuiApplication app(argc, argv);
    Qt3DExtras::Quick::Qt3DQuickWindow view;

        // Expose the window as a context property so we can set the aspect ratio
    view.engine()->qmlEngine()->rootContext()->setContextProperty("_window", &view);
    view.setSource(QUrl("qrc:/main.qml"));
    view.show();

    return app.exec();
}

资源.qrc
<RCC>
    <qresource prefix="/">
        <file>main.qml</file>
        <file>IronMan.qml</file>
        <file>man.obj</file>
        <file>man.png</file>
        <file>TextureAlphaMaterial.qml</file>
    </qresource>
    <qresource prefix="/shaders">
        <file>unlittexture.frag</file>
        <file>unlittexture.vert</file>
    </qresource>
</RCC>

main.qml
/****************************************************************************
**
** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB).
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt3D module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of The Qt Company Ltd nor the names of its
**     contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/

import QtQuick 2.1
import Qt3D.Core 2.0
import Qt3D.Render 2.9
import Qt3D.Input 2.0
import Qt3D.Extras 2.9

Entity {
    id: root
    objectName: "root"

    // Use the renderer configuration specified in ForwardRenderer.qml
    // and render from the mainCamera
    components: [
        RenderSettings {
            activeFrameGraph: RenderSurfaceSelector {
                id: renderSurfaceSelector

                CameraSelector {
                    id: cameraSelector
                    camera: camera
                    Viewport {
                        id: viewport
                        normalizedRect: Qt.rect(0, 0, 1, 1)
                        ClearBuffers {
                            buffers: ClearBuffers.AllBuffers
                            clearColor: "white"
                            NoDraw{}
                        }
                        LayerFilter {
                            layers: [opaqueLayer]

                        }
                        LayerFilter {
                            layers: [opaqueLayer]
                            filterMode: LayerFilter.DiscardAllMatchingLayers
                            NoDepthMask {}
                        }
                    }
                }
            }
        },
        InputSettings { }
    ]

    Camera {
        id: camera
        projectionType: CameraLens.PerspectiveProjection
        fieldOfView: 45
        nearPlane : 0.1
        farPlane : 1000.0
        position: Qt.vector3d( 0.0, 4.0, -5.0 )
        upVector: Qt.vector3d( 0.0, 1.0, 0.0 )
        viewCenter: Qt.vector3d( 0.0, 0.0, 0.0 )
    }

    FirstPersonCameraController { camera: camera }

    Entity {
        components: [
            PointLight {
                enabled: parent.enabled
                color: "black"
                intensity: 0
            }
        ]
    }

    Entity {
        PlaneMesh {
            id: groundMesh
            width: 50
            height: width
            meshResolution: Qt.size(2, 2)
        }

        Transform {
            id: groundTransform
            translation: Qt.vector3d(0, 0, 0)
        }

        Layer {
            id: opaqueLayer
        }

        PhongMaterial {
            id: material
            diffuse: Qt.rgba( 0.5, 0.5, 0.5, 1 )
            ambient: Qt.rgba( 0.5, 0.5, 0.5, 1 )
        }

        components: [
            groundMesh,
            groundTransform,
            material,
            opaqueLayer
        ]
    }
    IronMan {
        id: ironMan
    }
}

IronMan.qml
import Qt3D.Core 2.0
import Qt3D.Render 2.0
import Qt3D.Extras 2.0

import QtQml 2.14

Entity {
    id: root

    property vector3d position: Qt.vector3d(0, 0, 0)
    property real scale: 1.0
    property real rotationAngle: 0.0
    property vector3d rotationAxis: Qt.vector3d(1, 0, 0)
    property alias source: mesh.source
    property Material material

    components: [ transform, mesh, material ]

    Transform {
        id: transform
        scale: root.scale
        rotation: fromAxisAndAngle(root.rotationAxis, root.rotationAngle)
        translation: root.position
    }

    Mesh {
        id: mesh
        source: "qrc:/man.obj"
    }

    material: TextureAlphaMaterial {
        id: material

        opacity: 0.5
    }
}

TextureAlphaMaterial.qml
import Qt3D.Core 2.0
import Qt3D.Render 2.0

Material {
    id: root

    property real opacity: 1.

    parameters: [
        Parameter {
            name: "diffuseTexture"
            value: Texture2D {
                textureImages: [
                    TextureImage {
                        source: "qrc:/man.png"
                    }
                ]
            }
        }
    ]

    effect: Effect {
        id: rootEffect

        parameters: [
            Parameter
            {
                name: "opacity"
                value: root.opacity
            }
        ]
        techniques: [
            Technique {
                graphicsApiFilter {
                    api: GraphicsApiFilter.OpenGL
                    profile: GraphicsApiFilter.CoreProfile
                    majorVersion: 3
                    minorVersion: 1
                }

                filterKeys: [ FilterKey { name: "renderingStyle"; value: "forward" } ]

                renderPasses: [
                    RenderPass {
                        shaderProgram: ShaderProgram {
                            vertexShaderCode:   loadSource("qrc:/shaders/unlittexture.vert")
                            fragmentShaderCode: loadSource("qrc:/shaders/unlittexture.frag")
                        } 
                        renderStates: [
                            DepthTest {
                                depthFunction: DepthTest.LessOrEqual
                            },
                            NoDepthMask {
                            },
                            BlendEquation {
                                blendFunction: BlendEquation.Add
                            },
                            BlendEquationArguments {
                                sourceRgb: BlendEquationArguments.One
                                destinationRgb: BlendEquationArguments.OneMinusSourceAlpha
                                sourceAlpha: BlendEquationArguments.One
                                destinationAlpha: BlendEquationArguments.OneMinusSourceAlpha
                            }
                        ]
                    }
                ]
            }
        ]
    }
}

unlittexture.frag
#version 150 core

uniform sampler2D diffuseTexture;
uniform float opacity;

in vec3 position;
in vec2 texCoord;

out vec4 fragColor;


void main()
{
    fragColor = vec4(texture(diffuseTexture, texCoord).xyz * opacity, opacity);
}

unlittexture.vert
#version 150 core

in vec3 vertexPosition;
in vec2 vertexTexCoord;

out vec3 position;
out vec2 texCoord;

uniform mat4 modelView;
uniform mat4 mvp;

void main()
{
    vec3 t = vec3(vertexTexCoord, 1.0);
    texCoord = (t / t.z).xy;
    position = vec3(modelView * vec4(vertexPosition, 1.0));

    gl_Position = mvp * vec4(vertexPosition, 1.0);
}

笔记:

您可以分别用任何 3D 模型(使用 Blender 或任何其他 3D 软件导出到 obj)或映射纹理替换 man.obj 和 man.png。尽管如此,它们可以在 Florian's repository 上找到。或在 tripolskypetr's repository .

这是最终结果:

enter image description here

最佳答案

编辑 2
我修改了你的项目。它现在显示具有透明纹理的模型,您可以在 GitHub 上找到它。 .一定要去分行transparent_texture .
我没有实现允许动态设置透明度的功能,但我认为您可以从示例开始自己做到这一点。该模型也是未点亮的,即仅显示纹理而没有任何闪电,但通过查看其他 Qt3D Material 应该可以轻松实现一些简单的 phong 闪电。

原答案
Qt3D 不提供透明纹理对象的 Material ,这意味着您必须自己实现它。稍后我会回到那个。
简单透明
关于您的透明度问题,我使用了代码并得到了以下工作,但没有按钮:main.cpp :

#include <Qt3DQuickExtras/qt3dquickwindow.h>
#include <Qt3DQuick/QQmlAspectEngine>
#include <QGuiApplication>
#include <QQmlEngine>
#include <QQmlContext>

int main(int argc, char* argv[])
{
    QGuiApplication app(argc, argv);
    Qt3DExtras::Quick::Qt3DQuickWindow view;

    view.engine()->qmlEngine()->rootContext()->setContextProperty("_window", &view);
    view.setSource(QUrl("qrc:/main.qml"));
    view.show();

    return app.exec();
}
main.qml :
import QtQuick 2.1
import Qt3D.Core 2.0
import Qt3D.Render 2.9
import Qt3D.Input 2.0
import Qt3D.Extras 2.9

Entity {
    id: root
    objectName: "root"

    // Use the renderer configuration specified in ForwardRenderer.qml
    // and render from the mainCamera
    components: [
        RenderSettings {
            activeFrameGraph: RenderSurfaceSelector {
                id: renderSurfaceSelector

                CameraSelector {
                    id: cameraSelector
                    camera: camera
                    Viewport {
                        id: viewport
                        normalizedRect: Qt.rect(0, 0, 1, 1)
                        ClearBuffers {
                            buffers: ClearBuffers.AllBuffers
                            clearColor: "white"
                            NoDraw{}
                        }
                        LayerFilter {
                            layers: [opaqueLayer]

                        }
                        LayerFilter {
                            layers: [opaqueLayer]
                            filterMode: LayerFilter.DiscardAllMatchingLayers
                        }
                    }
                }
            }
        },
        // Event Source will be set by the Qt3DQuickWindow
        InputSettings { }
    ]

    Camera {
        id: camera
        projectionType: CameraLens.PerspectiveProjection
        fieldOfView: 45
        nearPlane : 0.1
        farPlane : 1000.0
        position: Qt.vector3d( 0.0, 4.0, -5.0 )
        upVector: Qt.vector3d( 0.0, 1.0, 0.0 )
        viewCenter: Qt.vector3d( 0.0, 0.0, 0.0 )
    }

    FirstPersonCameraController { camera: camera }

    Entity {
        components: [
            PointLight {
                enabled: parent.enabled
                color: "black"
                intensity: 0
            }
        ]
    }

    Entity {
        PlaneMesh {
            id: groundMesh
            width: 50
            height: width
            meshResolution: Qt.size(2, 2)
        }

        Transform {
            id: groundTransform
            translation: Qt.vector3d(0, 0, 0)
        }

        Layer {
            id: opaqueLayer
        }

        PhongMaterial {
            id: material
            diffuse: Qt.rgba( 0.5, 0.5, 0.5, 1 )
            ambient: Qt.rgba( 0.5, 0.5, 0.5, 1 )
        }

        components: [
            groundMesh,
            groundTransform,
            material,
            opaqueLayer
        ]
    }

    Entity {
        id: sphere1

        Mesh {
            id: man
            source: "qrc:/man.obj"
        }

        components: [
            man,
            matSphere1Material
        ]

        PhongAlphaMaterial {
            id: matSphere1Material
            alpha: 0.1
            ambient: Qt.rgba( 1, 1, 0, 0.0 )
            diffuse: Qt.rgba( 1, 1, 0, 0.0 )
            shininess: 50
        }
    }
}
我简化了您的示例以找出问题所在,看起来您在 main.cpp 中使用了错误的 QML 引擎。 .但我建议您尝试使用 Scene3DView 示例,因为透明度与您的设置类似(如果您需要 UI 中的按钮)。我经常使用这些示例并根据我的需要修改它们。我只是想让你开始使用我提供的代码。
如果你问自己为什么我有 LayerFilters在那里,结帐我的 answer这解释了为什么当您的场景中有透明对象时这是必要的。
透明纹理对象
这更困难(不幸的是我没有时间提供示例代码,也许当某些东西不起作用时开始然后提出问题)。在这里,您必须实现自己的着色器。 Qt3D 根本不提供任何考虑 alpha 的 read-made 实现。 q3dpostproc repository 总是对我帮助很大的一个存储库。 .您可以看到如何构建自己的 Qt3D Material 、加载自己的着色器并将参数传递给它们。
还有高级自定义 Material 示例,它可以为如何创建自定义着色器和传递参数提供很多帮助。
如果您想了解如何在着色器中对对象进行纹理处理,请查看 shader of QTextureMaterial和它的 code .我试图在 QML 中重新创建它,但它并没有立即起作用。
我建议您尝试使用 q3dpostproc 代码并尝试在那里对其中一个对象进行纹理处理(项目的结构有点复杂,因为它是一个展示,但过了一段时间它就变得有意义了)。它已经有一个使用纹理的着色器,因为它首先将所有内容绘制到屏幕外缓冲区,然后使用该纹理绘制屏幕。在您使用自己的着色器成功地对其中一个对象进行纹理处理后,您可以在其中执行以下操作:
fragColor = vec4(texture(...).xyz, 0.5);
这应该给你一个透明的纹理。您可能只需要更换 texture(...).xyz最后,当您想要正确点亮纹理时,可以使用更精细的东西。但是为此,您可以查看我链接的 Qt3D GitHub 存储库中的 phong 着色器或从 this repository 获取一个。或来自互联网的其他地方。
我希望这个信息帮助。

编辑 1
我修改了 q3dpostproc 代码以在 GitHub branch 中显示透明纹理.对象尚未点亮,但这应该使功能清晰。

关于qt - 在 QML 中控制带纹理的 3D 对象不透明度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61291143/

相关文章:

python - 无法导入 PyQt4.QtGui

c++ - 如何从自定义小部件类更改中央小部件?

c++ - BMP 纹理不显示

c# - 如何在 OpenTK 中使对象透明

c++ - GLEW 初始化失败

c++ - 启用/禁用QComboBox/QSpinBox时如何停止发出信号?

c++ - 与 PushButton 关联的 QLabel 不出现

c++ - 如何用qdbusxml2cpp生成同步接口(interface)类?

qt - 在新 Mac 上启动并运行 Qt5

c++ - 如何使用 Qt 类编译 rpcgen 文件?