Integrate iOS device camera and motion features to produce augmented reality experiences in your app or game using ARKit.

ARKit Documentation

Post

Replies

Boosts

Views

Activity

I want to convert this uikit code to swiftui
I want to convert this uikit code to swiftui but i have some problems and it doesn't work, please help me See LICENSE folder for this sample’s licensing information. Abstract: The sample app's main view controller. */ import UIKit import RealityKit import ARKit import Combine class ViewController: UIViewController, ARSessionDelegate { @IBOutlet var arView: ARView! var character: BodyTrackedEntity? let characterOffset: SIMD3<Float> = [-1.0, 0, 0] let characterAnchor = AnchorEntity() override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) arView.session.delegate = self guard ARBodyTrackingConfiguration.isSupported else { fatalError("This feature is only supported on devices with an A12 chip") } // 运行人体跟踪配置。 let configuration = ARBodyTrackingConfiguration() arView.session.run(configuration) arView.scene.addAnchor(characterAnchor) var cancellable: AnyCancellable? = nil cancellable = Entity.loadBodyTrackedAsync(named: "character/robot").sink( receiveCompletion: { completion in if case let .failure(error) = completion { print("Error: Unable to load model: \(error.localizedDescription)") } cancellable?.cancel() }, receiveValue: { (character: Entity) in if let character = character as? BodyTrackedEntity { character.scale = [1.0, 1.0, 1.0] self.character = character cancellable?.cancel() } else { print("Error: Unable to load model as BodyTrackedEntity") } }) } func session(_ session: ARSession, didUpdate anchors: [ARAnchor]) { for anchor in anchors { guard let bodyAnchor = anchor as? ARBodyAnchor else { continue } // 更新角色定位点位置的位置。 let bodyPosition = simd_make_float3(bodyAnchor.transform.columns.3) characterAnchor.position = bodyPosition + characterOffset characterAnchor.orientation = Transform(matrix: bodyAnchor.transform).rotation if let character = character, character.parent == nil { // 1. the body anchor was detected and // 2. the character was loaded. characterAnchor.addChild(character) } } } } Here's the code I wrote in SwiftUI import SwiftUI import RealityKit import ARKit import Combine struct ContentView : View { var body: some View { ARViewContainer().edgesIgnoringSafeArea(.all) } } struct ARViewContainer: UIViewRepresentable { var character: BodyTrackedEntity? let characterOffset: SIMD3<Float> = [-1.0, 0, 0] / let characterAnchor = AnchorEntity() func makeUIView(context: Context) -> ARView { let arView = ARView(frame: .zero) guard ARBodyTrackingConfiguration.isSupported else { fatalError("This feature is only supported on devices with an A12 chip") } let configuration = ARBodyTrackingConfiguration() arView.session.run(configuration) arView.scene.addAnchor(characterAnchor) var cancellable: AnyCancellable? = nil cancellable = Entity.loadBodyTrackedAsync(named: "character/robot").sink( receiveCompletion: { completion in if case let .failure(error) = completion { print("Error: Unable to load model: \(error.localizedDescription)") } cancellable?.cancel() }, receiveValue: { (character: Entity) in if let character = character as? BodyTrackedEntity { character.scale = [1.0, 1.0, 1.0] self.character = character cancellable?.cancel() } else { print("Error: Unable to load model as BodyTrackedEntity") } }) return arView } func updateUIView(_ uiView: ARView, context: Context) {} func session(_ session: ARSession, didUpdate anchors: [ARAnchor]) { for anchor in anchors { guard let bodyAnchor = anchor as? ARBodyAnchor else { continue } let bodyPosition = simd_make_float3(bodyAnchor.transform.columns.3) characterAnchor.position = bodyPosition + characterOffset characterAnchor.orientation = Transform(matrix: bodyAnchor.transform).rotation if let character = character, character.parent == nil { // 1. the body anchor was detected and // 2. the character was loaded. characterAnchor.addChild(character) } } } } #Preview { ContentView() }
3
0
309
Dec ’23
ARRaycastQuery and Front Facing Camera
Hi - I've searched all over the docs and might simply be missing something very big. Is raycasting available on front-facing True Depth camera like on the iPad Pro? I'm working on an application currently where I'm in ARFaceTrackingConfiguration and a simple raycast from the screen center is not yielding results. That same code in World configuration using the rear camera is producing results. My understanding, given the examples around bitmojis and face tracking, was that the front camera would have essentially the same depth data as the rear, just with less total distance available. Thanks for setting me straight! This is a very big deal for this particular project and I'm fearful I missed something in my pre-planning and investigation. Kane
1
0
311
Dec ’23
Using LiDAR DepthData with ARKit and SceneKit
Greetings! I have made use of Apple ARKit documentations to create a simple ARKit application which utilizes SceneKit (Tried Metal too) I am currently unsure of how to make use of SmoothedSceneDepth(SceneDepth) in general to acquire the DepthData from the DataMap acquired in the View. is there any particular method or way that I can access this data for displaying the depth. would be grateful with any inputs or suggestions. Thanks in advance
0
0
451
Dec ’23
The relationship between the deleted anchor and the newly created anchor (ARKit, ARPlaneAnchor))
Hello everyone I'm using the detectPlane feature in ARKit Get back ARPlaneAnchor from ARSCNViewDelegate (func renderer(SCNSceneRenderer, didAdd: SCNNode, for: ARAnchor), func renderer(SCNSceneRenderer, didUpdate: SCNNode, for: ARAnchor)), func renderer(SCNSceneRenderer, didRemove: SCNNode, for: ARAnchor) Occasionally ARPlaneAnchors are cleared by the call func renderer(SCNSceneRenderer, didRemove: SCNNode, for: ARAnchor) from ARKit I think that after deleting ARPlanAnchor, ARkit will recreate an ARPlaneAnchor in that location. so is there any relationship between deleted ARPlanAnchor and newly created ARPlaneAnchor? (Does the identifier, name, .... information reflect that relationship?)
0
0
207
Dec ’23
Does iPhone 13 work as well?
https://developer.apple.com/documentation/arkit/arkit_in_ios/content_anchors/visualizing_and_interacting_with_a_reconstructed_scene It says that fourth-generation iPad Pro running iPad OS 13.4 or later works because of the lidar. If iPhone 13 also has lidar then would it work too?
0
0
275
Dec ’23
ARView.debugOptions = .showStatistics Error: 5775
struct ARViewContainer: UIViewRepresentable { func makeUIView(context: Context) -> ARView { let arView = ARView(frame: .zero) arView.debugOptions = .showStatistics // Error: return arView } func updateUIView(_ uiView: ARView, context: Context) {} } -[MTLDebugRenderCommandEncoder validateCommonDrawErrors:]:5775: failed assertion `Draw Errors Validation Vertex Function(vsSdfFont): the offset into the buffer viewConstants that is bound at buffer index 4 must be a multiple of 256 but was set to 61840. '
1
0
456
Jan ’24
Correct way to convert AVDepthData.depthDataMap to gray depth image
Hi all. I can get disparity/depth data map from AVDepthData.depthDataMap and directly use it to generate a depth image. I found that under some situations, objects on the depth image cannot be clearly distinguished. When using disparity data, objects below 1 meter can't be clearly distinguished. When using depth data, objects larger than 1 meter can't be clearly distinguished. Does anyone know why this happens and how to fix it ?
2
0
312
Jan ’24
After adding gestures to the EntityModel inside ARView, there seems to be a memory leak when attempting to remove the EntityModel.
Example Code: struct ContentView : View { @State private var isRemoveEntityModel = false var body: some View { ZStack(alignment: .bottom) { ARViewContainer(isRemoveEntityModel: $isRemoveEntityModel).edgesIgnoringSafeArea(.all) Button { isRemoveEntityModel = true } label: { Image(systemName: "trash") .font(.system(size: 35)) .foregroundStyle(.orange) } } } } struct ARViewContainer: UIViewRepresentable { @Binding var isRemoveEntityModel: Bool let arView = ARView(frame: .zero) func makeUIView(context: Context) -> ARView { let model = CustomEntityModel() model.transform.translation.y = 0.05 model.generateCollisionShapes(recursive: true) arView.installGestures(.all, for: model) // --> After executing this line of code, it allows the deletion of a custom EntityModel in ARView.scene, but the deinit {} method of the custom EntityModel is not executed. let anchor = AnchorEntity(.plane(.horizontal, classification: .any, minimumBounds: SIMD2(0.2, 0.2))) anchor.children.append(model) arView.scene.anchors.append(anchor) return arView } func updateUIView(_ uiView: ARView, context: Context) { if isRemoveEntityModel { let customEntityModel = uiView.scene.findEntity(named: "Box_EntityModel") uiView.gestureRecognizers?.removeAll() // --->After executing this line of code, ARView.scene can correctly delete the CustomEntityModel, and the deinit {} method of CustomEntityModel can also be executed properly. However, other CustomEntityModels in ARView.scene lose their Gestures as well. customEntityModel?.removeFromParent() } } } class CustomEntityModel: Entity, HasModel, HasAnchoring, HasCollision { required init() { super.init() let mesh = MeshResource.generateBox(size: 0.1) let material = SimpleMaterial(color: .gray, isMetallic: true) self.model = ModelComponent(mesh: mesh, materials: [material]) self.name = "Box_EntityModel" } deinit { print("CustomEntityModel_remove") } }
0
0
276
Jan ’24
After adding gestures to the EntityModel inside ARView, there seems to be a memory leak when attempting to remove the EntityModel.
After adding gestures to the EntityModel, when it is necessary to remove the EntityModel, if the method uiView.gestureRecognizers?.removeAll() is not executed, the instance in memory cannot be cleared. However, executing this method affects gestures for other EntityModels in the ARView. Does anyone have a better method to achieve this? Example Code: struct ContentView : View { @State private var isRemoveEntityModel = false var body: some View { ZStack(alignment: .bottom) { ARViewContainer(isRemoveEntityModel: $isRemoveEntityModel).edgesIgnoringSafeArea(.all) Button { isRemoveEntityModel = true } label: { Image(systemName: "trash") .font(.system(size: 35)) .foregroundStyle(.orange) } } } } ARViewContainer: struct ARViewContainer: UIViewRepresentable { @Binding var isRemoveEntityModel: Bool let arView = ARView(frame: .zero) func makeUIView(context: Context) -> ARView { let model = CustomEntityModel() model.transform.translation.y = 0.05 model.generateCollisionShapes(recursive: true) __**arView.installGestures(.all, for: model)**__ // here--> After executing this line of code, it allows the deletion of a custom EntityModel in ARView.scene, but the deinit {} method of the custom EntityModel is not executed. arView.installGestures(.all, for: model) let anchor = AnchorEntity(.plane(.horizontal, classification: .any, minimumBounds: SIMD2<Float>(0.2, 0.2))) anchor.children.append(model) arView.scene.anchors.append(anchor) return arView } func updateUIView(_ uiView: ARView, context: Context) { if isRemoveEntityModel { let customEntityModel = uiView.scene.findEntity(named: "Box_EntityModel") // --->After executing this line of code, ARView.scene can correctly delete the CustomEntityModel, and the deinit {} method of CustomEntityModel can also be executed properly. However, other CustomEntityModels in ARView.scene lose their Gestures as well. __** uiView.gestureRecognizers?.removeAll()**__ customEntityModel?.removeFromParent() } } } CustomEntityModel: class CustomEntityModel: Entity, HasModel, HasAnchoring, HasCollision { required init() { super.init() let mesh = MeshResource.generateBox(size: 0.1) let material = SimpleMaterial(color: .gray, isMetallic: true) self.model = ModelComponent(mesh: mesh, materials: [material]) self.name = "Box_EntityModel" } deinit { **print("CustomEntityModel_remove")** } }
0
0
392
Jan ’24
Place Entity in the Middle of a Table in VisionOS
Hello Guys, I am currently stuck on understanding how I can place a 3D Entity from a USDZ file or a Reality Composer Pro project in the middle of a table in a mixed ImmersiveSpace. When I use the AnchorEntity(.plane(.horizontal, classification: .table, minimumBounds: SIMD2<Float>(0.2, 0.2))) it just places it somewhere on the table and not in the middle and not in the orientation of the table so the edges are not aligned. Has anybody got a clue on how to to this? I would be very thankful for a response, Thanks
0
2
392
Jan ’24
ARKit in high resolution
Hope to get support for ARKit in high resolution using this api rightnow: NSArray<ARVideoFormat *> *supportedVideoFormats = [ARWorldTrackingConfiguration supportedVideoFormats]; Qs: If a high-resolution ARVideoFormat is not included in the supportedVideoFormats, is it still supported?"
1
0
214
Jan ’24
AR - Draw on a virtual 3D object
Hello everyone, I'm working on an AR app. There I load a 3D model of an human arm and place it on a QR code (ARImageAnchor). The user can now move the model and change its texture. Is it possible to draw on this 3D model with my finger? I have seen videos where models react to a touch. But I don't just want to touch the model, I want to create a small sphere exactly at the point where I touch the model, for example. I would like to be able to draw a line on the arm. My model has a CollisionShape.
0
0
261
Jan ’24
Roomplan exceeded scene size limit error. (RoomCaptureSession.CaptureError.exceedSceneSizeLimit)
Error: RoomCaptureSession.CaptureError.exceedSceneSizeLimit Apple Documentation Explanation: An error that indicates when the scene size grows past the framework’s limitations. Issue: This error is popping up in my iPhone 14 Pro (128 GB) after a few roomplan scans are done. This error shows up even if the room size is small. It occurs immediately after I start the RoomCaptureSession after the relocalisation of previous AR session (in world tracking configuration). I am having trouble understanding exactly why this error shows and how to debug/solve it. Does anyone have any idea on how to approach to this issue?
0
1
399
Jan ’24
Is ARGeoTrackingConfiguration always more accurate than ARWorldTrackingConfiguration for world scale AR?
We are working on a world scale AR app that leverages the device location and heading to place objects in the streets, so that they are correctly and stably anchored to certain locations. Since the geo-tracking imagery is only available in certain cities and areas, we are trying to figure out how to fallback when geo-tracking is not available as the device move away, to still retain good AR camera accuracy. We might need to come up with some algorithm using the device GPS, to line up the ARCamera with our objects. Question: Does geo-tracking always provide greater than or equal to the accuracy of world tracking, for a GPS outdoor AR experience? If so, we can simply use the ARGeoTrackingConfiguration for the entire time, and rely on the ARView keeping itself aligned. Otherwise, we need to switch between it and ARWorldTrackingConfiguration when geo-tracking is not available and/or its accuracy is low, then roll our own algorithm to keep the camera aligned. Thanks.
2
0
455
Jan ’24
Use CoreImage filters on Vision Pro (visionOS) view
I have an iOS app that uses (camera) video feed and applies CoreImage filters to simulate a specific real world effect (for educational purposes). Now I wanted to make a similar app for visionOS and apply the same CoreImage filters to the content (live view) users sees while wearing Apple Vision Pro headset. Is there a way to do it with current APIs and what would you recommend? I saw that we cannot get video feed from camera(s), is there a way to do it with ARKit and applying the filters somehow using that? I know visionOS is a young/fresh platform but any help would be great! Thank you!
1
0
868
Jan ’24
WorldTrackingProvider's queryDeviceAnchor is not giving correct deviceAnchor
I'm constructing a RealityView where I'd like to display content in front of user's face. When testing, I found that the deviceAnchor I initially get was wrong, so I implement following code to wait until the deviceAnchor I get from worldTrackingProvider has the correct value: private let arkitSession = ARKitSession() private let worldTrackingProvider = WorldTrackingProvider() var body: some View { RealityView { content, attachments in Task { do { // init worldTrackingProvider try await arkitSession.run([worldTrackingProvider]) // wait until deviceAnchor returns correct info var deviceAnchor : DeviceAnchor? // continuously get deviceAnchor and check until it's valid while (deviceAnchor == nil || !checkDeviceAnchorValid(Transform(matrix: deviceAnchor!.originFromAnchorTransform).translation)) { deviceAnchor = worldTrackingProvider.queryDeviceAnchor(atTimestamp: CACurrentMediaTime()) } let cameraTransform = Transform(matrix: deviceAnchor!.originFromAnchorTransform) // ...codes that update my entity's translation } catch { print("Error: \(error)") } } } } private func checkDeviceAnchorValid(_ translation: SIMD3<Float>) -> Bool { // codes that check if the `deviceAnchor` has a valid translation. } However, I found that sometimes I can't get out from the while loop defined above. Not because my rules inside checkDeviceAnchorValid func are too strict, but because the translation I get from deviceAnchor is always invalid(it is [0,0,0] and never changed) Why is this happening? Is this a known issue? I wonder if I can get recalled when the worldTrackingProvider returns the correct deviceAnchor,
2
0
594
Jan ’24