Skip to content

Instantly share code, notes, and snippets.

@Matt54
Created June 22, 2024 23:14
Show Gist options
  • Select an option

  • Save Matt54/25f80d2bcd90aa32a29375a13b19692e to your computer and use it in GitHub Desktop.

Select an option

Save Matt54/25f80d2bcd90aa32a29375a13b19692e to your computer and use it in GitHub Desktop.
A rotating disco ball RealityView created from a LowLevelMesh
import RealityKit
import SwiftUI
struct DiscoBallRealityView: View {
@State private var currentEntity: Entity?
@State private var morphFactor: Float = 0.0
@State private var frameDuration: TimeInterval = 0.0
@State private var lastUpdateTime = CACurrentMediaTime()
static let animationFrameDuration: TimeInterval = 1.0 / 120.0
private let timer = Timer.publish(every: animationFrameDuration, on: .main, in: .common).autoconnect()
var body: some View {
GeometryReader3D { proxy in
RealityView { content in
let size = content.convert(proxy.frame(in: .local), from: .local, to: .scene).extents
let radius = Float(0.5 * size.x)
currentEntity = try! createSphereEntity(morphFactor: 0, radius: radius)
if let entity = currentEntity {
content.add(entity)
}
} update: { content in
let size = content.convert(proxy.frame(in: .local), from: .local, to: .scene).extents
let radius = Float(0.5 * size.x)
if let modelComponent = try? getModelComponent(morphFactor: morphFactor, radius: radius) {
currentEntity?.components.set(modelComponent)
}
}
.onReceive(timer) { _ in
let currentTime = CACurrentMediaTime()
frameDuration = currentTime - lastUpdateTime
lastUpdateTime = currentTime
let morphAmount = Float(frameDuration)
morphFactor = morphFactor + morphAmount
}
}
}
func createSphereEntity(morphFactor: Float, radius: Float = 0.5) throws -> Entity {
let modelComponent = try getModelComponent(morphFactor: morphFactor, radius: radius)
let entity = Entity()
entity.name = "Sphere"
entity.components.set(modelComponent)
entity.scale *= 0.3
return entity
}
func getModelComponent(morphFactor: Float, radius: Float = 0.5) throws -> ModelComponent {
let lowLevelMesh = try sphereMesh(morphFactor: morphFactor, radius: radius)
let resource = try MeshResource(from: lowLevelMesh)
var material = PhysicallyBasedMaterial()
material.baseColor.tint = .init(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
material.roughness.scale = 0.0
material.metallic.scale = 1.0
material.faceCulling = .none
return ModelComponent(mesh: resource, materials: [material])
}
func sphereMesh(morphFactor: Float, radius: Float = 0.5) throws -> LowLevelMesh {
let latitudeBands = 30
let longitudeBands = 50
let vertexCount = (latitudeBands + 1) * (longitudeBands + 1)
let indexCount = latitudeBands * longitudeBands * 6
var desc = MyVertex.descriptor
desc.vertexCapacity = vertexCount
desc.indexCapacity = indexCount
let mesh = try LowLevelMesh(descriptor: desc)
let rotationMatrix = getRotationMatrix(angle: morphFactor*0.8)
mesh.withUnsafeMutableBytes(bufferIndex: 0) { rawBytes in
let vertices = rawBytes.bindMemory(to: MyVertex.self)
var vertexIndex = 0
for latNumber in 0...latitudeBands {
let theta = Float(latNumber) * Float.pi / Float(latitudeBands)
let sinTheta = sin(theta)
let cosTheta = cos(theta)
for longNumber in 0...longitudeBands {
let phi = Float(longNumber) * 2 * Float.pi / Float(longitudeBands)
let sinPhi = sin(phi)
let cosPhi = cos(phi)
let x = cosPhi * sinTheta
let y = cosTheta
let z = sinPhi * sinTheta
var position = SIMD3<Float>(x, y, z) * radius
position = simd_mul(rotationMatrix, position)
let color = 0xFFFFFFFF
vertices[vertexIndex] = MyVertex(position: position, color: UInt32(color))
vertexIndex += 1
}
}
}
mesh.withUnsafeMutableIndices { rawIndices in
let indices = rawIndices.bindMemory(to: UInt32.self)
var index = 0
for latNumber in 0..<latitudeBands {
for longNumber in 0..<longitudeBands {
let first = (latNumber * (longitudeBands + 1)) + longNumber
let second = first + longitudeBands + 1
indices[index] = UInt32(first)
indices[index + 1] = UInt32(second)
indices[index + 2] = UInt32(first + 1)
indices[index + 3] = UInt32(second)
indices[index + 4] = UInt32(second + 1)
indices[index + 5] = UInt32(first + 1)
index += 6
}
}
}
let meshBounds = BoundingBox(min: [-radius, -radius, -radius], max: [radius, radius, radius])
mesh.parts.replaceAll([
LowLevelMesh.Part(
indexCount: indexCount,
topology: .triangleStrip,
bounds: meshBounds
)
])
return mesh
}
func getRotationMatrix(angle: Float) -> simd_float3x3 {
let rotationY = simd_float3x3(
SIMD3<Float>(cos(angle), 0, sin(angle)),
SIMD3<Float>(0, 1, 0),
SIMD3<Float>(-sin(angle), 0, cos(angle))
)
return rotationY
}
}
struct MyVertex {
var position: SIMD3<Float> = .zero
var color: UInt32 = .zero
static var vertexAttributes: [LowLevelMesh.Attribute] = [
.init(semantic: .position, format: .float3, offset: MemoryLayout<Self>.offset(of: \.position)!),
.init(semantic: .color, format: .uchar4Normalized_bgra, offset: MemoryLayout<Self>.offset(of: \.color)!)
]
static var vertexLayouts: [LowLevelMesh.Layout] = [
.init(bufferIndex: 0, bufferStride: MemoryLayout<Self>.stride)
]
static var descriptor: LowLevelMesh.Descriptor {
var desc = LowLevelMesh.Descriptor()
desc.vertexAttributes = MyVertex.vertexAttributes
desc.vertexLayouts = MyVertex.vertexLayouts
desc.indexType = .uint32
return desc
}
}
#Preview {
DiscoBallRealityView()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment