RealityKit
的文档包含了以下结构体:OcclusionMaterial
、SimpleMaterial
和UnlitMaterial
,用于向ModelEntity
添加材料。
或者您可以加载已附有材质的模型。
我想在程序中向ModelEntity
添加自定义材料/纹理。如何在不将材料添加到Reality Composer或其他3D软件中的模型的情况下实现这一点?
RealityKit
的文档包含了以下结构体:OcclusionMaterial
、SimpleMaterial
和UnlitMaterial
,用于向ModelEntity
添加材料。
或者您可以加载已附有材质的模型。
我想在程序中向ModelEntity
添加自定义材料/纹理。如何在不将材料添加到Reality Composer或其他3D软件中的模型的情况下实现这一点?
更新日期:2023年6月24日
目前RealityKit中有八种类型的材质:
MaterialX
,仅适用于visionOS)在这里,我使用了两种macOS实现(SwiftUI和Cocoa)来演示如何以编程方式分配RealityKit材质。
import SwiftUI
import RealityKit
struct VRContainer : NSViewRepresentable {
let arView = ARView(frame: .zero)
let anchor = AnchorEntity()
func makeNSView(context: Context) -> ARView {
var smpl = SimpleMaterial()
smpl.color.tint = .blue
smpl.metallic = 0.7
smpl.roughness = 0.2
var pbr = PhysicallyBasedMaterial()
pbr.baseColor.tint = .green
let mesh: MeshResource = .generateBox(width: 0.5,
height: 0.5,
depth: 0.5,
cornerRadius: 0.02,
splitFaces: true)
let box = ModelEntity(mesh: mesh, materials: [smpl, pbr])
box.orientation = Transform(pitch: .pi/4,
yaw: .pi/4, roll: 0.0).rotation
anchor.addChild(box)
arView.scene.anchors.append(anchor)
arView.environment.background = .color(.black)
return arView
}
func updateNSView(_ view: ARView, context: Context) { }
}
struct ContentView: View {
var body: some View {
VRContainer().ignoresSafeArea()
}
}
import Cocoa
import RealityKit
class ViewController: NSViewController {
@IBOutlet var arView: ARView!
override func awakeFromNib() {
let box = try! Experience.loadBox()
var simpleMat = SimpleMaterial()
simpleMat.color = .init(tint: .blue, texture: nil)
simpleMat.metallic = .init(floatLiteral: 0.7)
simpleMat.roughness = .init(floatLiteral: 0.2)
var pbr = PhysicallyBasedMaterial()
pbr.baseColor = .init(tint: .green, texture: nil)
let mesh: MeshResource = .generateBox(width: 0.5,
height: 0.5,
depth: 0.5,
cornerRadius: 0.02,
splitFaces: true)
let boxComponent = ModelComponent(mesh: mesh,
materials: [simpleMat, pbr])
box.steelBox?.children[0].components.set(boxComponent)
box.steelBox?.orientation = Transform(pitch: .pi/4,
yaw: .pi/4,
roll: 0).rotation
arView.scene.anchors.append(box)
}
}
我们知道,在SceneKit中有5种不同的着色模型,因此我们可以使用RealityKit的SimpleMaterial
、PhysicallyBasedMaterial
和UnlitMaterial
来生成我们习惯使用的这五种着色器。
让我们看看它是什么样子:
SCNMaterial.LightingModel.blinn – SimpleMaterial(color: . gray,
roughness: .float(0.5),
isMetallic: false)
SCNMaterial.LightingModel.lambert – SimpleMaterial(color: . gray,
roughness: .float(1.0),
isMetallic: false)
SCNMaterial.LightingModel.phong – SimpleMaterial(color: . gray,
roughness: .float(0.0),
isMetallic: false)
SCNMaterial.LightingModel.physicallyBased – PhysicallyBasedMaterial()
// all three shaders (`.constant`, `UnlitMaterial` and `VideoMaterial `)
// don't depend on lighting
SCNMaterial.LightingModel.constant – UnlitMaterial(color: .gray)
– VideoMaterial(avPlayer: avPlayer)
splitFaces: Bool
参数可以帮助您应用6X纹理。 - Andy Jazz