Contents

MeshInstancesComponent

A component that performs GPU instancing on the model of the same entity.

Declaration

struct MeshInstancesComponent

Overview

RealityKit applies the transform hierarchy of this component’s entity to the individual transforms specified by LowLevelInstanceData. You can think of these instances as sub-entities of the entity you apply this component to, meaning LowLevelInstanceData is in the local space of that same entity.

Due to this transform hierarchy, use the entity’s scale, position, and orientation to transform the overall group of instances. Use the transforms within LowLevelInstanceData to transform the individual instances.

To use this component, create a LowLevelInstanceData instance and use the convenience initializer, init(mesh:modelID:instances:bounds:) to create the MeshInstancesComponent directly from a MeshResource.

let entity = try await ModelEntity(named: "robot")

guard let mesh = entity.components[ModelComponent.self]?.mesh else { return }

let instanceCount = 10
let instanceData = try LowLevelInstanceData(instanceCount: instanceCount)

instanceData.withMutableTransforms { transforms in
    for i in 0..<instanceCount {

        let instanceAngle = 2 * .pi * Float(i) / Float(instanceCount)
        let radialTranslation: SIMD3<Float> = [-sin(instanceAngle), cos(instanceAngle), 0] * 2

        // Position each robot around a circle.
        let transform = Transform(
            scale: .one / 10,
            rotation: simd_quatf(angle: instanceAngle, axis: [0, 0, 1]),
            translation: radialTranslation
        )
        transforms[i] = transform.matrix
    }
}

// Instance only the first model.
let modelID = mesh.contents.models.first?.id

// Create the component using the convenience initializer.
let instancesComponent = try MeshInstancesComponent(
    mesh: mesh,
    modelID: modelID,
    instances: instanceData
)
entity.components.set(instancesComponent)

// Place the instance group into position.
entity.position = [0, 0, -1]

[Image]

Topics

Structures

Initializers

Subscripts

See Also

Render configuration