qt-Quick3D筆記之官方例程Runtimeloader Example運行筆記

qt-Quick3D筆記之官方例程Runtimeloader Example運行筆記

文章目錄

  • qt-Quick3D筆記之官方例程Runtimeloader Example運行筆記
    • 1.例程運行效果
    • 2.例程縮略圖
    • 3.項目文件列表
    • 4.main.qml
    • 5.main.cpp
    • 6.CMakeLists.txt

1.例程運行效果

在這里插入圖片描述

運行該項目需要自己準備一個模型文件

2.例程縮略圖

在這里插入圖片描述

3.項目文件列表

runtimeloader/
├── CMakeLists.txt
├── main.cpp
├── main.qml
├── qml.qrc
└── runtimeloader.pro1 directory, 5 files

4.main.qml

// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clauseimport QtQuick
import QtQuick.Window
import QtQuick.Controls
import QtQuick.Layoutsimport Qt.labs.platform
import QtCoreimport QtQuick3D
import QtQuick3D.Helpers
import QtQuick3D.AssetUtils// 創建一個窗口根節點,設置窗口大小和顯示狀態
Window {id: windowRootvisible: truewidth: 1280height: 720property url importUrl; // 用于導入模型的URL//! [base scene] 基礎場景View3D {id: view3Danchors.fill: parent // 填充父窗口environment: SceneEnvironment {id: envbackgroundMode: SceneEnvironment.SkyBox // 背景模式為天空盒lightProbe: Texture {textureData: ProceduralSkyTextureData{} // 使用程序化天空紋理}InfiniteGrid {visible: helper.gridEnabled // 是否顯示網格gridInterval: helper.gridInterval // 網格間隔}}camera: helper.orbitControllerEnabled ? orbitCamera : wasdCamera // 根據控制器選擇相機// 設置方向光源DirectionalLight {eulerRotation.x: -35eulerRotation.y: -90castsShadow: true // 啟用陰影}Node {id: orbitCameraNodePerspectiveCamera {id: orbitCamera // 軌道相機}}// 第一人稱相機(WASD控制)PerspectiveCamera {id: wasdCameraonPositionChanged: {// 更新相機的近遠裁剪面let distance = position.length()if (distance < 1) {clipNear = 0.01clipFar = 100} else if (distance < 100) {clipNear = 0.1clipFar = 1000} else {clipNear = 1clipFar = 10000}}}//! [base scene]// 重置視圖的函數function resetView() {if (importNode.status === RuntimeLoader.Success) {helper.resetController()}}//! [instancing] 實例化RandomInstancing {id: instancinginstanceCount: 30 // 設置實例數量position: InstanceRange {property alias boundsDiameter: helper.boundsDiameterfrom: Qt.vector3d(-3*boundsDiameter, -3*boundsDiameter, -3*boundsDiameter); // 位置范圍to: Qt.vector3d(3*boundsDiameter, 3*boundsDiameter, 3*boundsDiameter)}color: InstanceRange { from: "black"; to: "white" } // 顏色范圍}//! [instancing]QtObject {id: helperproperty real boundsDiameter: 0 // 場景邊界的直徑property vector3d boundsCenter // 場景中心property vector3d boundsSize // 場景大小property bool orbitControllerEnabled: true // 是否啟用軌道控制器property bool gridEnabled: gridButton.checked // 是否啟用網格property real cameraDistance: orbitControllerEnabled ? orbitCamera.z : wasdCamera.position.length() // 相機與中心的距離property real gridInterval: Math.pow(10, Math.round(Math.log10(cameraDistance)) - 1) // 網格間隔計算// 更新場景邊界信息function updateBounds(bounds) {boundsSize = Qt.vector3d(bounds.maximum.x - bounds.minimum.x,bounds.maximum.y - bounds.minimum.y,bounds.maximum.z - bounds.minimum.z)boundsDiameter = Math.max(boundsSize.x, boundsSize.y, boundsSize.z)boundsCenter = Qt.vector3d((bounds.maximum.x + bounds.minimum.x) / 2,(bounds.maximum.y + bounds.minimum.y) / 2,(bounds.maximum.z + bounds.minimum.z) / 2 )wasdController.speed = boundsDiameter / 1000.0 // 更新控制器速度wasdController.shiftSpeed = 3 * wasdController.speedwasdCamera.clipNear = boundsDiameter / 100wasdCamera.clipFar = boundsDiameter * 10view3D.resetView() // 重置視圖}// 重置控制器function resetController() {orbitCameraNode.eulerRotation = Qt.vector3d(0, 0, 0)orbitCameraNode.position = boundsCenterorbitCamera.position = Qt.vector3d(0, 0, 2 * helper.boundsDiameter)orbitCamera.eulerRotation = Qt.vector3d(0, 0, 0)orbitControllerEnabled = true}// 切換控制器function switchController(useOrbitController) {if (useOrbitController) {let wasdOffset = wasdCamera.position.minus(boundsCenter)let wasdDistance = wasdOffset.length()let wasdDistanceInPlane = Qt.vector3d(wasdOffset.x, 0, wasdOffset.z).length()let yAngle = Math.atan2(wasdOffset.x, wasdOffset.z) * 180 / Math.PIlet xAngle = -Math.atan2(wasdOffset.y, wasdDistanceInPlane) * 180 / Math.PIorbitCameraNode.position = boundsCenterorbitCameraNode.eulerRotation = Qt.vector3d(xAngle, yAngle, 0)orbitCamera.position = Qt.vector3d(0, 0, wasdDistance)orbitCamera.eulerRotation = Qt.vector3d(0, 0, 0)} else {wasdCamera.position = orbitCamera.scenePositionwasdCamera.rotation = orbitCamera.sceneRotationwasdController.focus = true}orbitControllerEnabled = useOrbitController}}//! [runtimeloader] 運行時加載器RuntimeLoader {id: importNodesource: windowRoot.importUrl // 導入模型的URLinstancing: instancingButton.checked ? instancing : null // 實例化開關onBoundsChanged: helper.updateBounds(bounds) // 更新場景邊界}//! [runtimeloader]//! [bounds] 場景邊界Model {parent: importNodesource: "#Cube" // 默認使用立方體模型materials: PrincipledMaterial {baseColor: "red" // 設置基礎顏色為紅色}opacity: 0.2 // 設置模型透明度visible: visualizeButton.checked && importNode.status === RuntimeLoader.Success // 根據條件顯示模型position: helper.boundsCenterscale: Qt.vector3d(helper.boundsSize.x / 100,helper.boundsSize.y / 100,helper.boundsSize.z / 100)}//! [bounds]//! [status report] 狀態報告Rectangle {id: messageBoxvisible: importNode.status !== RuntimeLoader.Success // 如果導入失敗,顯示錯誤消息color: "red"width: parent.width * 0.8height: parent.height * 0.8anchors.centerIn: parentradius: Math.min(width, height) / 10opacity: 0.6Text {anchors.fill: parentfont.pixelSize: 36text: "Status: " + importNode.errorString + "\nPress \"Import...\" to import a model" // 顯示錯誤信息color: "white"wrapMode: Text.WraphorizontalAlignment: Text.AlignHCenterverticalAlignment: Text.AlignVCenter}}//! [status report]}//! [camera control] 相機控制OrbitCameraController {id: orbitControllerorigin: orbitCameraNodecamera: orbitCameraenabled: helper.orbitControllerEnabled // 根據狀態啟用或禁用軌道控制器}WasdController {id: wasdControllercontrolledObject: wasdCameraenabled: !helper.orbitControllerEnabled // 根據狀態啟用或禁用WASD控制器}//! [camera control]// 界面控制面板Pane {width: parent.widthcontentHeight: controlsLayout.implicitHeightRowLayout {id: controlsLayoutButton {id: importButtontext: "Import..."onClicked: fileDialog.open() // 打開文件對話框focusPolicy: Qt.NoFocus}Button {id: resetButtontext: "Reset view"onClicked: view3D.resetView() // 重置視圖focusPolicy: Qt.NoFocus}Button {id: visualizeButtoncheckable: truetext: "Visualize bounds" // 顯示場景邊界focusPolicy: Qt.NoFocus}Button {id: instancingButtoncheckable: truetext: "Instancing" // 開啟實例化focusPolicy: Qt.NoFocus}Button {id: gridButtontext: "Show grid" // 顯示網格focusPolicy: Qt.NoFocuscheckable: truechecked: false}Button {id: controllerButtontext: helper.orbitControllerEnabled ? "Orbit" : "WASD" // 切換控制器onClicked: helper.switchController(!helper.orbitControllerEnabled)focusPolicy: Qt.NoFocus}RowLayout {Label {text: "Material Override"}ComboBox {id: materialOverrideComboBoxtextRole: "text"valueRole: "value"implicitContentWidthPolicy: ComboBox.WidestTextonActivated: env.debugSettings.materialOverride = currentValue // 選擇材質覆蓋model: [{ value: DebugSettings.None, text: "None"},{ value: DebugSettings.BaseColor, text: "Base Color"},{ value: DebugSettings.Roughness, text: "Roughness"},{ value: DebugSettings.Metalness, text: "Metalness"},{ value: DebugSettings.Diffuse, text: "Diffuse"},{ value: DebugSettings.Specular, text: "Specular"},{ value: DebugSettings.ShadowOcclusion, text: "Shadow Occlusion"},{ value: DebugSettings.Emission, text: "Emission"},{ value: DebugSettings.AmbientOcclusion, text: "Ambient Occlusion"},{ value: DebugSettings.Normals, text: "Normals"},{ value: DebugSettings.Tangents, text: "Tangents"},{ value: DebugSettings.Binormals, text: "Binormals"},{ value: DebugSettings.F0, text: "F0"}]}}CheckBox {text: "Wireframe" // 啟用或禁用線框模式checked: env.debugSettings.wireframeEnabledonCheckedChanged: {env.debugSettings.wireframeEnabled = checked}}}}// 文件對話框,允許用戶選擇glTF模型文件FileDialog {id: fileDialognameFilters: ["glTF files (*.gltf *.glb)", "All files (*)"]onAccepted: importUrl = file // 選擇文件后導入Settings {id: fileDialogSettingscategory: "QtQuick3D.Examples.RuntimeLoader"property alias folder: fileDialog.folder}}// 調試視圖切換按鈕Item {width: debugViewToggleText.implicitWidthheight: debugViewToggleText.implicitHeightanchors.right: parent.rightLabel {id: debugViewToggleTexttext: "Click here " + (dbg.visible ? "to hide DebugView" : "for DebugView")anchors.right: parent.rightanchors.top: parent.top}MouseArea {anchors.fill: parentonClicked: dbg.visible = !dbg.visible // 切換調試視圖可見性DebugView {y: debugViewToggleText.height * 2anchors.right: parent.rightsource: view3Did: dbgvisible: false}}}
}

5.main.cpp

// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifdef HAS_MODULE_QT_WIDGETS
# include <QApplication>
#endif
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickWindow>
#include <QtQuick3D/qquick3d.h>int main(int argc, char *argv[])
{
#ifdef HAS_MODULE_QT_WIDGETSQApplication app(argc, argv);
#elseQGuiApplication app(argc, argv);
#endifapp.setOrganizationName("The Qt Company");app.setOrganizationDomain("qt.io");app.setApplicationName("Runtime Asset Loading Example");const auto importUrl = argc > 1 ? QUrl::fromLocalFile(argv[1]) : QUrl{};if (importUrl.isValid())qDebug() << "Importing" << importUrl;QSurfaceFormat::setDefaultFormat(QQuick3D::idealSurfaceFormat(4));QQmlApplicationEngine engine;const QUrl url(QStringLiteral("qrc:/main.qml"));engine.load(url);if (engine.rootObjects().isEmpty()) {qWarning() << "Could not find root object in" << url;return -1;}QObject *topLevel = engine.rootObjects().value(0);QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);if (window)window->setProperty("importUrl", importUrl);return app.exec();
}

6.CMakeLists.txt

# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clausecmake_minimum_required(VERSION 3.16)
project(runtimeloader LANGUAGES CXX)set(CMAKE_AUTOMOC ON)find_package(Qt6 REQUIRED COMPONENTS Core Gui Quick Quick3D Widgets)qt_add_executable(runtimeloadermain.cpp
)set_target_properties(runtimeloader PROPERTIESWIN32_EXECUTABLE TRUEMACOSX_BUNDLE TRUE
)target_link_libraries(runtimeloader PUBLICQt::CoreQt::GuiQt::QuickQt::Quick3D
)if(TARGET Qt::Widgets)target_compile_definitions(runtimeloader PUBLICHAS_MODULE_QT_WIDGETS)target_link_libraries(runtimeloader PUBLICQt::Widgets)
endif()qt_add_qml_module(runtimeloaderURI ExampleVERSION 1.0QML_FILES main.qmlNO_RESOURCE_TARGET_PATH
)install(TARGETS runtimeloaderBUNDLE  DESTINATION .RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
)qt_generate_deploy_qml_app_script(TARGET runtimeloaderOUTPUT_SCRIPT deploy_scriptMACOS_BUNDLE_POST_BUILDNO_UNSUPPORTED_PLATFORM_ERRORDEPLOY_USER_QML_MODULES_ON_UNSUPPORTED_PLATFORM
)
install(SCRIPT ${deploy_script})

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/68074.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/68074.shtml
英文地址,請注明出處:http://en.pswp.cn/web/68074.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

以太坊入門【詳解】

以太坊的組成部分 P2P網絡&#xff1a;以太坊在以太坊網絡上運行&#xff0c;該網絡可在TCP端口30303上尋址&#xff0c;并運行一個協議。交易&#xff1a;以太坊交易時網絡消息&#xff0c;其中包括發送者&#xff0c;接受者&#xff0c;值和數據的有效載荷以太坊虛擬機&…

實驗十四 EL和JSTL

實驗十四 EL和JSTL 一、實驗目的 1、掌握EL表達式的使用 2、掌握JSTL的使用 二、實驗過程 1、在數據庫Book中建立表Tbook&#xff0c;包含圖書ID&#xff0c;圖書名稱&#xff0c;圖書價格。實現在bookQuery.jsp頁面中模糊查詢圖書&#xff0c;如果圖書的價格在50元以上&#…

安裝和卸載RabbitMQ

我的飛書:https://rvg7rs2jk1g.feishu.cn/docx/SUWXdDb0UoCV86xP6b3c7qtMn6b 使用Ubuntu環境進行安裝 一、安裝Erlang 在安裝RabbitMQ之前,我們需要先安裝Erlang,RabbitMQ需要Erlang的語言支持 #安裝Erlang sudo apt-get install erlang 在安裝的過程中,會彈出一段信息,此…

音視頻多媒體編解碼器基礎-codec

如果要從事編解碼多媒體的工作&#xff0c;需要準備哪些更為基礎的內容&#xff0c;這里幫你總結完。 因為數據類型不同所以編解碼算法不同&#xff0c;分為圖像、視頻和音頻三大類&#xff1b;因為流程不同&#xff0c;可以分為編碼和解碼兩部分&#xff1b;因為編碼器實現不…

ML基礎-Jupyter notebook中的魔法命令

在 Jupyter Notebook 或 IPython 環境中&#xff0c;“魔法命令”&#xff08;Magic Commands&#xff09;是一些以百分號&#xff08;%&#xff09;或驚嘆號&#xff08;!)開頭的特殊命令&#xff0c;用于執行一些與代碼運行環境相關的操作&#xff0c;而不僅僅是執行普通的 P…

【Unity2D 2022:UI】創建滾動視圖

一、創建Scroll View游戲對象 在Canvas畫布下新建Scroll View游戲對象 二、為Content游戲對象添加Grid Layout Group&#xff08;網格布局組&#xff09;組件 選中Content游戲物體&#xff0c;點擊Add Competent添加組件&#xff0c;搜索Grid Layout Group組件 三、調整Grid La…

9-收納的知識

[ComponentOf(typeof(xxx))]組件描述&#xff0c;表示是哪個實體的組件 [EntitySystemOf(typeof(xxx))] 系統描述 [Event(SceneType.Demo)] 定義事件&#xff0c;在指定場景的指定事件發生后觸發 [ChildOf(typeof(ComputersComponent))] 標明是誰的子實體 [ResponseType(na…

數據庫系統概念第六版記錄 一

1.關系型數據庫 關系型數據庫&#xff08;Relational Database&#xff0c;簡稱 RDB&#xff09;是基于關系模型的一種數據庫&#xff0c;它通過表格的形式來組織和存儲數據。每個表由若干行&#xff08;記錄&#xff09;和列&#xff08;字段&#xff09;組成&#xff0c;數據…

Vue前端開發-pinia之Actions插件

Store中的Actions部分&#xff0c;用于定義操作屬性的方法&#xff0c;類似于組件中的methods部分&#xff0c;它與Getters都可以操作State屬性&#xff0c;但在定義方法時&#xff0c;Getters是對State屬性進行加工處理&#xff0c;再返回使用&#xff0c;屬于內部計算;Action…

生成式AI安全最佳實踐 - 抵御OWASP Top 10攻擊 (下)

今天小李哥將開啟全新的技術分享系列&#xff0c;為大家介紹生成式AI的安全解決方案設計方法和最佳實踐。近年來生成式 AI 安全市場正迅速發展。據IDC預測&#xff0c;到2025年全球 AI 安全解決方案市場規模將突破200億美元&#xff0c;年復合增長率超過30%&#xff0c;而Gartn…

一個開源 GenBI AI 本地代理(確保本地數據安全),使數據驅動型團隊能夠與其數據進行互動,生成文本到 SQL、圖表、電子表格、報告和 BI

一、GenBI AI 代理介紹&#xff08;文末提供下載&#xff09; github地址&#xff1a;https://github.com/Canner/WrenAI 本文信息圖片均來源于github作者主頁 在 Wren AI&#xff0c;我們的使命是通過生成式商業智能 &#xff08;GenBI&#xff09; 使組織能夠無縫訪問數據&…

JAVA架構師進階之路

JAVA架構師進階之路 前言 苦于網絡上充斥的各種java知識&#xff0c;多半是互相抄襲&#xff0c;導致很多后來者在學習java知識中味同嚼蠟&#xff0c;本人閑暇之余整理了進階成為java架構師所必須掌握的核心知識點&#xff0c;后續會不斷擴充。 廢話少說&#xff0c;直接上正…

java程序員面試自身優缺點,詳細說明

程序員面試大廠經常被問到的Java異常機制問題,你搞懂了嗎運行時異常:運行時異常是可能被程序員避免的異常。與檢查性相反,運行時異常可以在編譯時被忽略。錯誤(ERROR):錯誤不是異常,而是脫離程序員控制的問題。錯誤通常在代碼中容易被忽略。例如:當棧溢出時,一個錯誤就發生了,它…

C++六大默認成員函數

C六大默認成員函數 默認構造函數默認析構函數RAII技術RAII的核心思想優點示例應用場景 默認拷貝構造深拷貝和淺拷貝 默認拷貝賦值運算符移動構造函數&#xff08;C11起&#xff09;默認移動賦值運算符&#xff08;C11起&#xff09;取地址及const取地址操作符重載取地址操作符重…

Java 2024年面試總結(持續更新)

目錄 最近趁著金三銀四面了五六家公司吧&#xff0c;也整理了一些問題供大家參考一下&#xff08;適合經驗三年左右的&#xff09;。 面試問題&#xff08;答案是我自己總結的&#xff0c;不一定正確&#xff09;&#xff1a; 總結&#xff1a; 最近趁著金三銀四面了五六家公…

防火墻的安全策略

1.VLAN 2屬于辦公區;VLAN 3屬于生產區&#xff0c;創建時間段 [FW]ip address-set BG type object [FW-object-address-set-BG]address 192.168.1.0 mask 25 [FW]ip address-set SC type object [FW-object-address-set-SC]address 192.168.1.129 mask 25 [FW]ip address-se…

工作流項目BPMN.JS_Question梳理

工作流項目 想了解如果候選人熟悉工作流技術、bpmn.js和Flowable工作流引擎&#xff0c;面試官會對哪些信息感興趣。我需要分析這個問題&#xff0c;并給出一個全面而結構化的回答。 首先&#xff0c;用戶可能希望了解作為前端面試官&#xff0c;應該關注候選人哪些方面的知識和…

windows下搭建鴻蒙OS應用開發環境

一、前言 HUAWEI DevEco Studio 是華為推出的一款集成開發環境&#xff08;IDE&#xff09;&#xff0c;主要用于開發基于華為鴻蒙操作系統&#xff08;HarmonyOS&#xff09;的應用。作為華為開發者工具的核心之一&#xff0c;DevEco Studio 提供了一個多功能的開發平臺&…

MacBook Pro(M1芯片)Qt環境配置

MacBook Pro&#xff08;M1芯片&#xff09;Qt環境配置 1、準備 試圖寫一個跨平臺的桌面應用&#xff0c;此時想到了使用Qt&#xff0c;于是開始了搭建開發環境&#xff5e; 在M1芯片的電腦上安裝&#xff0c;使用brew工具比較方便 Apple Silicon&#xff08;ARM/M1&#xf…

Sqlserver DBCC Check 遇到Msg 3853報錯涉及sys.columns和sys.objects信息不匹配的解決方法

對數據庫CacheDBMSIntl執行DBCC checkcatalog(‘CacheDBMSIntl’)時遇到報錯如下 Msg 3853, Level 16, State 1, Line 7 Attribute (object_id1071830442) of row (object_id1071830442,column_id1) in sys.columns does not have a matching row (object_id1071830442) in sy…