How can i play a USDZ entity animation in reverse? I have tried to put a negative value to the speed as I was doing in SceneKit to make the animation reverse play but it did not work. here is my code:
import SwiftUI
import RealityKit
struct ImmersiveView: View {
@State var entity = Entity()
@State var openDoor: Bool = true
var body: some View {
RealityView { content in
if let mainDoor = try? await Entity(named: "Door.usdz") {
if let frame = mainDoor.findEntity(named: "DoorFrame")
{
frame.position = [0, 0, -8]
frame.orientation = simd_quatf(angle: (270 * (.pi / 180)), axis: SIMD3(x: 1, y: 0, z: 0))
content.add(frame)
entity = frame.findEntity(named: "Door")!
entity.components.set(InputTargetComponent(allowedInputTypes: .indirect))
entity.components.set(HoverEffectComponent())
let entityModel = entity.children[0]
entityModel.generateCollisionShapes(recursive: true)
}
}
}
.gesture(
SpatialTapGesture()
.targetedToEntity(entity)
.onEnded { value in
print(value)
if openDoor == true
{
let animController = entity.playAnimation(entity.availableAnimations[0], transitionDuration: 0 , startsPaused: true)
animController.speed = 1.0
animController.resume()
openDoor = false
}
else
{
let animController = entity.playAnimation(entity.availableAnimations[0], transitionDuration: 0 , startsPaused: true)
animController.speed = -1.0 // it does not work to reverse
animController.resume()
openDoor = true
}
}
)
}
}
The Door should open with first click which is already happening and close with second click which is not happening as it does not reverse play the animation
RealityKit
RSS for tagSimulate and render 3D content for use in your augmented reality apps using RealityKit.
Posts under RealityKit tag
200 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
I have some strange behavior in my app. When I set the position to .zero you can see the sphere normally. But when I change it to any number it doesn't matter which and how small. The Sphere isn't visible or in the view.
The RealityView
import SwiftUI
import RealityKit
import RealityKitContent
struct TheSphereOfDoomRV: View {
@StateObject var viewModel: SphereViewModel = SphereViewModel()
let sphere = SphereEntity(radius: 0.25, materials: [SimpleMaterial(color: .red, isMetallic: true)], name: "TheSphere")
var body: some View {
RealityView { content, attachments in
content.add(sphere)
} update: { content, attachments in
sphere.scale = SIMD3<Float>(x: viewModel.scale, y: viewModel.scale, z: viewModel.scale)
} attachments: {
VStack {
Text("The Sphere of Doom is one of the most powerful Objects. You can interact with him in every way you can imagine ").multilineTextAlignment(.center)
Button {
} label: {
Text("Play Video!")
}
}.tag("description")
}.modifier(GestureModifier()).environmentObject(viewModel)
}
}
SphereEntity:
import Foundation
import RealityKit
import RealityKitContent
class SphereEntity: Entity {
private let sphere: ModelEntity
@MainActor
required init() {
sphere = ModelEntity()
super.init()
}
init(radius: Float, materials: [Material], name: String) {
sphere = ModelEntity(mesh: .generateSphere(radius: radius), materials: materials)
sphere.generateCollisionShapes(recursive: false)
sphere.components.set(InputTargetComponent())
sphere.components.set(HoverEffectComponent())
sphere.components.set(CollisionComponent(shapes: [.generateSphere(radius: radius)]))
sphere.name = name
super.init()
self.addChild(sphere)
self.position = .zero // .init(x: Float, y: Float, z: Float) and [Float, Float, Float] doesn't work ...
}
}
Hello,
I've been trying to render these models in a VisionOS app using RealityKit's Model3D API. The heart seem to appear dark all the time. Any thoughts on why this would happen?
Color.clear
.overlay {
Model3D(named: modelName, bundle: realityKitContentBundle) { model in
model.resizable()
.scaledToFit()
.rotation3DEffect(
Rotation3D(
eulerAngles: .init(angles: orientation, order: .xyz)
)
)
.frame(depth: modelDepth)
.offset(z: -modelDepth / 2)
.accessibilitySortPriority(1)
} placeholder: {
ProgressView()
.offset(z: -modelDepth * 0.75)
}
}
.dragRotation(yawLimit: .degrees(120), pitchLimit: .degrees(20))
.offset(z: modelDepth)
I am working on an AR app on iOS. I found this issue and can't find a quick solution at this moment nor do I find any insight into what is happening.
Context:
The AR app contains a 3D model of a sphere that is cut in half. The models are created with a 3D modeling software.
Additional context:
The sphere model is placed inside the environment. When the user enters the sphere then the sphere materials are set to video materials containing this jungle-like content visible in the video.
The vertical center of the sphere is the floor on which the user moves and looks around. Each ARPlaneAnchor is connected to an ARAnchorEntity with its ModelEntity (Plane) for visualization and sphere placement.
The bug (video):
https://www.youtube.com/shorts/58860U1IkhM
As the user moves inside the sphere parts of the video material start to show the square plane camera feed parts (background).
What has been tried:
changing material type on the floor plane (physically based material seems a little less bad)
changing the culling of the materials (no effect). the issue is not related to z-fighting. When a solid material for the floor plane is used then the flickering is not visible. When a solid material with alpha is used then both are visible (alpha material and flickering background)
editing the .usdz file (does not work at all) (changing shadows and other properties)
checked .usdz file with usdz tools (usdzconvert - all tests have passed and fixed opacity did not help)
Changing the video type (.mp4 to .mov)
Google & ChatGPT
Similar issues:
How do I eliminate flickering ...
Plane entity's grounding shadow flicking in RealityKit
AR flickering
Observations:
The flickering background is always tied to the floor plane (can provide screenshots). This seems to highlight either a point of contact with the 3D floor plane or something else.
The flickering happens at some certain angle and position. It does not happen all the time in all positions which is weird.
This problem didn't happen with the old sphere 3D file. The difference is a new 3D-generated floor plane WHICH IS DISABLED. It seems that even if it is disabled it is still being used somehow.
I had a similar issue where the floor planes would change color (the color tone would go more light and dark). This issue was solved by disabling automatic shadow rendering. Shadow rendering inside an object does not seem to work properly. The main difference is that the previous issue changed the color brightness, not color transparency (translucent), and that the whole plane color was changed and not some part of it.
Logging all the available planes shows only the expected planes (1-3, of which 1-2 two are floor planes and 1 is an image plane).
Any ideas, solutions, or feedback is welcome.
SO Post:
https://stackoverflow.com/questions/78139934/realitykit-plane-flickering-bug-in-model-with-videomaterial
Thank you for your time.
Does anyone know how I can disable foveation for an ImmersiveSpace? I'm aware that I could use a CompositorLayer and my own Metal rendering to control foveation, but I'm hoping that I can configure an existing/underlying LayerRenderer (or similar) to disable it for an immersive scene.
Or if there's another approach I should be taking, any pointers are appreciated. Thank you!
I have a volumetric window that I am using to display 3D content.
The issue I have is that the rotation of the 3D models will rotate when the user moves the window. I want the rotation across the Y-axis to remain fixed when the user repositions the window. Is that possible?
Also, is there a way to visually debug the walls of the 3D volume window?
I'm trying to add dynamic shadows by adding a directional light to the scene.
I implemented a POC based on the latest documentation.
Basically, the way shadows are being rendered in RealityKit is by a adding a ModelEntity into an AnchorEntity with a target of type planes.
The result is that I'm getting shadows that are terribly flickering.
I'd add that in SceneKit, there are many more shadow-related properties that let you tweak the look and feel of the shadows, and it's not hard to get a decent shadow there.
I'm wondering if having accurate dynamic shadows is possible in RealityKit and if not, if there's a plan to fix it in the next RealityKit version.
I've been trying to animate the OpacityComponent to fade in/out entities in my scene. I've tried animating the component with an AnimationResource as well as tried animating with a custom System. Both worked fine in the simulator, but failed on device.
AnimationResource: When I animated the opacity of an entity using an animation with an opacity bind target, the entity would not change opacity until I physically looked away from the object. It's almost as if the device keeps an entity visible for as long as you keep looking at it, but once you look away it plays the animation.
System: I created a custom system that manually changes the opacity over time, however, on device the gradual fade of the entity doesn't work. Instead, the entity literally pops in/out of view instead of fading.
Can someone explain exactly how this component is supposed to be used? The simulator plays the animations exactly the way I would expect, but on device it's completely different.
Edit:
I'm trying to change the opacity of entities with a VideoMaterial added to a ModelComponent. The fade animations are performed at certain points in the video that are triggered by an AVPlayer time boundary observer.
Hi all,
I took bunch of photos using Apple's 'Capture Sample' iOS app. Even though the all images in .HEIC/HEIF file format that CLI tool logs the bunch of the following errors and couldn't find any solution.
1-) HEIF file is expected.
2-) *** Assertion failure in OCReturn OCNonModularSPI_CMPhoto_readResolution(const OCHeicReadHandle, const NSURL *__strong, uint64_t *, uint64_t *)(), CMPhoto+NonModularSPI.m:1271
I'm using RealityKit for a scene with many static and dynamic ModelEntitys simulating physics. When all the entities have simple collision generated from .generateCollisionShapes I don't see any issues, but for some entities I need much more complex and accurate collision. For this I've been using ShapeResource.generateStaticMesh with the mesh's data (2769 positions, 16272 face indices in this case), which works exactly as desired with a low entity count. However once there are 600+ dynamic entities introducing even one static entity with complex collision will reliably trigger a crash when colliding with one of the dynamic entities (not necessarily on first contact, but inevitably after multiple collisions).
If I arbitrarily limit the number of entities to a max of around 500 it seems to prevent the issue from happening, though the likelihood seems to increase with the number of entities so there may be a low probability of it triggering even at 500 entities that I haven't hit while testing.
If physx imposes some kind of entity or collision face/shape limit or something like that I'd at least like to know exactly what it is, but ideally there's a way to work around this. Right now my "fix" is just arbitrarily restricting the entity count in a way that limits what my app can do.
The crash triggers inside
0x00000001a6790dfc in physx::PxcDiscreteNarrowPhasePCM(physx::PxcNpThreadContext&, physx::PxcNpWorkUnit const&, physx::Gu::Cache&, physx::PxsContactManagerOutput&) ()
which looks like this (crash line has an -> arrow at the bottom)
CoreRE`physx::PxcDiscreteNarrowPhasePCM:
...
0x1a6790df0 <+668>: mov x1, x24
0x1a6790df4 <+672>: bl 0x1a67913d8 ; physx::PxcNpCacheStreamPair::reserve(unsigned int)
0x1a6790df8 <+676>: ldrb w8, [x23]
-> 0x1a6790dfc <+680>: str w8, [x0, #0x20]
I'm working on an application for viewing AMF models on macOS, using RealityKit. AMF supports several different ways to color models, including per-vertex color (where the color of a triangle is interpolated from vertex to vertex) as well as per-face color (where the color of the triangle is the same across the entire face).
I'm trying to figure out how to support those color models using a RealityKit mesh. Apple's documentation (https://developer.apple.com/documentation/realitykit/modifying-realitykit-rendering-using-custom-materials) talks about per-vertex colors, but I haven't found a way to create a mesh that includes per-vertex colors, other than use a texture map (which might be the correct solution).
Can someone give me some pointers?
I want to render a dense point cloud in Mixed Reality view using RealityKit. How could I achieve this, if this is possible? It seems to only support rendering mesh geometries with triangle faces.
Hello is it possible to change the default position for the spatial keyboard in visionOS for an input field. At least do anyone know how is this position established?
Why does PhotogrammetrySession.isSupported return true if Object Capture is supported?
It would be great if you could use PhotogrammetrySession on iOS devices without lidar and feed it a folder of pictures to make a 3D model.
Thanks!
Hello, I'm interested in using the iOS on-device object capture API for photogrammetry, however I would like to integrate it in a web app.
I understand that web apps cannot usually access system-level APIs, so I am unsure of whether or not this would be feasible to implement. I would greatly appreciate for any pointers in the right direction.
Thank you!
With the advent of the third dimension, I wanted to know wether if it's currently possible to display the flat swiftUI Views with some thickness in xrOS?
While the .frame(depth: CGFloat?) does the job for Views in general, I am eager for a more granular level of control at the pixel-specific level.
I was hoping that there are lower level APIs to achieve this & I've looked into the fairly new layerEffect shader API, yet it seems it's incapable of setting the depths of pixels...
I can't get a 3D model to spin inside a swiftUI 2D view..
I had for example:
Model3D(named: "Cupcake")
.rotationEffect(Angle(degrees: rotationAngle))
But I'm unsure where to implement something like
rotationAngle += 5
(I'm used to Unity and would put that in Update())
Really new to the Vision OS coding. We tried to create a customized experience just like what apple did in the system Environments or the Disney did in its app ( it seems they put user in a carefully made 3d model). Do we need to make a 3d model for the environment and how to put it around the user sphere like the skybox?
Is there a way to give a "Primitive Shape" entity created through Reality Composer Pro a ModelComponent?
I have a custom ShaderGraphMaterial assigned to a primitive shape in my RC Pro scene hierarchy, and I'd like to tweak the inputs of this material programatically. I found a great example of the behavior I'm looking for here: https://developer.apple.com/videos/play/wwdc2023/10273/?time=1862
@State private var sliderValue: Float = 0.0
Slider(value: $sliderValue, in: (0.0)...(1.0))
.onChange(of: sliderValue) { _, _ in
guard let terrain = rootEntity.findEntity(named: "DioramaTerrain"),
var modelComponent = terrain.components[ModelComponent.self],
var shaderGraphMaterial = modelComponent.materials.first
as? ShaderGraphMaterial else { return }
do {
try shaderGraphMaterial.setParameter(name: "Progress", value: .float(sliderValue))
modelComponent.materials = [shaderGraphMaterial]
terrain.components.set(modelComponent)
} catch { }
}
}
However, when I try applying this example to my use-case, my project's equivalent to this line fails to execute:
var modelComponent = terrain.components[ModelComponent.self]
The only difference I can see between my case and this example is my entity is a primitive shape, whereas the example uses a model reference to a .usdz file. Is there some way to update a primitive shape entity to contain this ModelComponent in its set of components so I can reference + update its materials programmatically?
Hello,
I've been tinkering with PortalComponent on visionOS a bit but noticed that the content of the WorldComponent is always clipped to the mesh geometry of whatever entities have the PortalComponent applied. Now I'm wondering if there is any way or trick to allow contents of the portal to peek out – similar to the Encounter Dinosaurs experience on Vision Pro (I assume it also uses PortalComponent?).
I saw that PortalComponent has a clippingPlane property (https://developer.apple.com/documentation/realitykit/portalcomponent/clippingplane-swift.property). But so far I haven't been able to achieve a perceptible visual difference with it.
If possible I would like to avoid hacky tricks using duplicate meshes or similar to achieve this.
Thanks for any hints!