You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在RealityKit中访问.usdz加载的ModelEntity几何数据?

从ModelEntity中提取几何数据(位置、法线等)

你已经拿到了对应属性的AnyMeshBuffer,接下来只需要根据缓冲区对应的几何属性,用get(type:)方法指定正确的数据类型就能提取出实际数据。下面是完整的可运行示例:

完整代码示例

import RealityKit

extension ModelEntity {
    func extractGeometryDetails() {
        guard let meshContents = model?.mesh.contents else { return }
        
        for meshModel in meshContents.models {
            for part in meshModel.parts {
                for (attribute, buffer) in part.buffers {
                    // 根据属性类型匹配对应的数据结构
                    switch attribute {
                    case MeshBufferAttribute.position:
                        if let positionBuffer = buffer.get(type: SIMD3<Float>.self) {
                            let vertexPositions = Array(positionBuffer)
                            print("顶点位置数量:\(vertexPositions.count),首个位置:\(vertexPositions[0])")
                        }
                    case MeshBufferAttribute.normal:
                        if let normalBuffer = buffer.get(type: SIMD3<Float>.self) {
                            let normals = Array(normalBuffer)
                            print("法线数量:\(normals.count),首个法线:\(normals[0])")
                        }
                    case MeshBufferAttribute.texcoord0:
                        if let uvBuffer = buffer.get(type: SIMD2<Float>.self) {
                            let uvCoords = Array(uvBuffer)
                            print("UV坐标数量:\(uvCoords.count),首个UV:\(uvCoords[0])")
                        }
                    case MeshBufferAttribute.color:
                        if let colorBuffer = buffer.get(type: SIMD4<Float>.self) {
                            let colors = Array(colorBuffer)
                            print("顶点颜色数量:\(colors.count),首个颜色:\(colors[0])")
                        }
                    default:
                        print("未处理的几何属性:\(attribute)")
                    }
                }
            }
        }
    }
}

// 使用方式(假设已加载好ModelEntity)
// let targetEntity = try! ModelEntity.load(named: "yourModel.usdz")
// targetEntity.extractGeometryDetails()

关键说明

  • MeshBufferAttribute定义了所有标准几何属性的标识符,对应模型里的位置、法线、UV、颜色等数据
  • buffer.get(type:)需要传入对应的数据类型:
    • 位置、法线是三维向量,用SIMD3<Float>
    • UV坐标是二维向量,用SIMD2<Float>
    • 顶点颜色是四维向量(RGBA),用SIMD4<Float>
  • 通过Array(buffer)可以把MeshBuffer转换成Swift原生数组,方便后续遍历或处理

内容的提问来源于stack exchange,提问作者Runt8

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 17:03:14