For an AR experience I'm working on, I want to have a "camera view" that shows annotations based on the user's location. If the user is in a certain area, show the annotation.
I'm able to do something like this using below
extension ViewController: AnnotationManagerDelegate {
func session(_ session: ARSession, cameraDidChangeTrackingState camera: ARCamera) {
print("camera did change tracking state: \(camera.trackingState)")
let annotationLocation = CLLocation()
let point = CGPoint(x: annotationLocation.coordinate.longitude, y: annotationLocation.coordinate.latitude)
let features = mapView.visibleFeatures(at: point);
if let score = features.first(where: { $0.attributes["score"] as! Int >= 5 }) {
// ...
But in my AR view, I want to hide the map - not show it. When I try setting mapView.isHidden = true - the query always fails.
This makes sense because the query is for visible features. How can instead hide the map, but still query tiles for features?
Go into Mapbox Studio https://www.mapbox.com/studio/ and create a new map style and remove all of the layers. You can style a Mapbox map to be a single solid color (land, water, roads, etc.), which is what you need. If you need to toggle between a map and a blank map, simply toggle between styles.
let basicMap = URL(string: "mapbox://styles/mapbox/outdoors-v9")
let blankMap = URL(string: "yourCustomURLFromMapboxStudio")
let mapView = MGLMapView(frame: view.bounds, styleURL: blankMap)
Related
I'm trying to place a 3D model on top of a recognized image with ARKit and RealityKit - all programmatically. Before I start the ARView I'm downloading the model I want to show when the reference image is detected.
This is my current setup:
override func viewDidLoad() {
super.viewDidLoad()
arView.session.delegate = self
// Check if the device supports the AR experience
if (!ARConfiguration.isSupported) {
TLogger.shared.error_objc("Device does not support Augmented Reality")
return
}
guard let qrCodeReferenceImage = UIImage(named: "QRCode") else { return }
let detectionImages: Set<ARReferenceImage> = convertToReferenceImages([qrCodeReferenceImage])
let configuration = ARWorldTrackingConfiguration()
configuration.detectionImages = detectionImages
arView.session.run(configuration, options: [.resetTracking, .removeExistingAnchors])
}
I use the ARSessionDelegate to get notified when a new image anchor was added which means the reference image got detected:
func session(_ session: ARSession, didAdd anchors: [ARAnchor]) {
print("Hello")
for anchor in anchors {
guard let imageAnchor = anchor as? ARImageAnchor else { return }
let referenceImage = imageAnchor.referenceImage
addEntity(self.localModelPath!)
}
}
However, the delegate method never gets called while other delegate functions like func session(ARSession, didUpdate: ARFrame) are getting called so I assume that the session just doesn't detect the image. The image resolution is good and the printed image the big so it should definitely get recognized by the ARSession. I also checked that the image has been found before adding it to the configuration.
Can anyone lead me in the right direction here?
It looks like you have your configuration set up correctly. Your delegate-function should be called when the reference image is recognized. Make sure your configuration isn't overwritten at any point in your code.
I have an app that generates point cloud from multiple ARFrame. It appears that the camera used to capture the image has dynamic white balance, and can change it in the middle of a capture session.
How do I configure ARView, ARSession, or ARCamera to force it to lock white balance for the duration of the session?
I have access to the following parameters, but do not see anything related to white balance.
var arView: ARView!
let session: ARSession = arView.session
var sampleFrame: ARFrame = session.currentFrame!
let camera = sampleFrame.camera
func configureSessionAndRun() {
arView.automaticallyConfigureSession = false
let configuration = ARWorldTrackingConfiguration()
configuration.sceneReconstruction = .meshWithClassification
configuration.frameSemantics = .smoothedSceneDepth
configuration.planeDetection = [.horizontal, .vertical]
configuration.environmentTexturing = .automatic
arView.session.run(configuration)
}
There are only two AR View's properties that could help, but they are just gettable, not settable:
let frame = arView.session.currentFrame
frame?.camera.exposureDuration // { get }
frame?.camera.exposureOffset // { get }
I'm implementing a custom style for my google maps view for a bus transit app I'm developing in XCode 9 w/ Swift 4. Whenever I load a map view, it always takes a little less than a second to load the custom style and I'm not sure what's causing this to happen.
Here's the effect I'm describing:
As you can see, the tan background is the default style for google's mapview, and it's visible for only a small period of time.
Here's my code that implements the map view:
class StopPredictionVC: UIViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setUpMapView()
}
private func setUpMapView() {
let stopLatitude = Double(stop!.lat)
let stopLongitude = Double(stop!.lon)
let camera = GMSCameraPosition.camera(withLatitude: stopLatitude!, longitude: stopLongitude!, zoom: 16.4)
let frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
mapView = GMSMapView.map(withFrame: frame, camera: camera)
let nightModeEnabled = APIWrapper.sharedInstance.settings.nightMode!
if nightModeEnabled {
mapView.mapStyle(withFilename: "nightStyle", andType: "json")
} else {
mapView.mapStyle(withFilename: "mapStyle", andType: "json")
}
let marker = GMSMarker()
marker.icon = #imageLiteral(resourceName: "marker")
marker.appearAnimation = .pop
marker.position = CLLocationCoordinate2D(latitude: stopLatitude!, longitude: stopLongitude!)
marker.title = "Bus Stop Name"
marker.snippet = "Example description"
marker.map = mapView
buildRoute(routePath: routeConfig!.path)
view.addSubview(mapView)
}
}
extension GMSMapView {
func mapStyle(withFilename name: String, andType type: String) {
do {
if let styleURL = Bundle.main.url(forResource: name, withExtension: type) {
self.mapStyle = try GMSMapStyle(contentsOfFileURL: styleURL)
} else {
NSLog("Unable to find style.json")
}
} catch {
NSLog("One or more of the map styles failed to load. \(error)")
}
}
}
buildRoute(routePath:) is a function that builds the blue colored path on the road if anyone was wondering.
Obviously this isn't a huge bug, but it's quite frustrating to see every time I load a map view. Anyone see anything in my code that could be causing this?
You call it inside viewWillAppear it has 2 problems , first it's called after viewDidLoad (has some delay) , second it may be called every time the VC is shown such as returning from a push / dismiss Modal
so call setUpMapView inside viewDidLoad
note this buildRoute(routePath: routeConfig!.path) should be in a background queue if it calls any web service or do any long job inside mainQueue
BTW i may also try to load
GMSMapStyle(contentsOfFileURL: styleURL)
in background thread and after load set in mainQueue and that only if using GMSMapStyle is allowed inside a back thread
I have scanned and trained multiple real world objects. I do have the ARReferenceObject and the app detects them fine.
The issue that I'm facing is when an object doest not have distinct, vibrant features it takes few seconds to return a detection result, which I can understand. Now, I want the app to show a bounding box and an activity indicator on top the object while it is trying to detect it.
I do not see any information regarding this. Also, if there is any way to get the time when detection starts or the confidence percentage of the object being detected.
Any help is appreciated.
It is possible to show a boundingBox in regard to the ARReferenceObject prior to it being detected; although I am not sure why you would want to do that (in advance anyway).
For example, assuming your referenceObject was on a horizontal surface you would first need to place your estimated bounding box on the plane (or use some other method to place it in advance), and in the time it took to detect the ARPlaneAnchor and place the boundingBox it is most likely that your model would already have been detected.
Possible Approach:
As you are no doubt aware an ARReferenceObject has a center, extent and scale property as well as a set of rawFeaturePoints associated with the object.
As such we can create our own boundingBox node based on some of the sample code from Apple in Scanning & Detecting 3D Objects and create our own SCNNode which will display a bounding box of the approximate size of the ARReferenceObject which is stored locally prior to it being detected.
Note you will need to locate the 'wireframe_shader' from the Apple Sample Code for the boundingBox to render transparent:
import Foundation
import ARKit
import SceneKit
class BlackMirrorzBoundingBox: SCNNode {
//-----------------------
// MARK: - Initialization
//-----------------------
/// Creates A WireFrame Bounding Box From The Data Retrieved From The ARReferenceObject
///
/// - Parameters:
/// - points: [float3]
/// - scale: CGFloat
/// - color: UIColor
init(points: [float3], scale: CGFloat, color: UIColor = .cyan) {
super.init()
var localMin = float3(Float.greatestFiniteMagnitude)
var localMax = float3(-Float.greatestFiniteMagnitude)
for point in points {
localMin = min(localMin, point)
localMax = max(localMax, point)
}
self.simdPosition += (localMax + localMin) / 2
let extent = localMax - localMin
let wireFrame = SCNNode()
let box = SCNBox(width: CGFloat(extent.x), height: CGFloat(extent.y), length: CGFloat(extent.z), chamferRadius: 0)
box.firstMaterial?.diffuse.contents = color
box.firstMaterial?.isDoubleSided = true
wireFrame.geometry = box
setupShaderOnGeometry(box)
self.addChildNode(wireFrame)
}
required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) Has Not Been Implemented") }
//----------------
// MARK: - Shaders
//----------------
/// Sets A Shader To Render The Cube As A Wireframe
///
/// - Parameter geometry: SCNBox
func setupShaderOnGeometry(_ geometry: SCNBox) {
guard let path = Bundle.main.path(forResource: "wireframe_shader", ofType: "metal", inDirectory: "art.scnassets"),
let shader = try? String(contentsOfFile: path, encoding: .utf8) else {
return
}
geometry.firstMaterial?.shaderModifiers = [.surface: shader]
}
}
To display the bounding box you you would then do something like the following, noting that in my example I have the following variables:
#IBOutlet var augmentedRealityView: ARSCNView!
let configuration = ARWorldTrackingConfiguration()
let augmentedRealitySession = ARSession()
To display the boundingBox prior to detection of the actual object itself, you would call the func loadBoundigBox in viewDidLoad e.g:
/// Creates A Bounding Box From The Data Available From The ARObject In The Local Bundle
func loadBoundingBox(){
//1. Run Our Session
augmentedRealityView.session = augmentedRealitySession
augmentedRealityView.delegate = self
//2. Load A Single ARReferenceObject From The Main Bundle
if let objectURL = Bundle.main.url(forResource: "fox", withExtension: ".arobject"){
do{
var referenceObjects = [ARReferenceObject]()
let object = try ARReferenceObject(archiveURL: objectURL)
//3. Log it's Properties
print("""
Object Center = \(object.center)
Object Extent = \(object.extent)
Object Scale = \(object.scale)
""")
//4. Get It's Scale
let scale = CGFloat(object.scale.x)
//5. Create A Bounding Box
let boundingBoxNode = BlackMirrorzBoundingBox(points: object.rawFeaturePoints.points, scale: scale)
//6. Add It To The ARSCNView
self.augmentedRealityView.scene.rootNode.addChildNode(boundingBoxNode)
//7. Position It 0.5m Away From The Camera
boundingBoxNode.position = SCNVector3(0, -0.5, -0.5)
//8. Add It To The Configuration
referenceObjects.append(object)
configuration.detectionObjects = Set(referenceObjects)
}catch{
print(error)
}
}
//9. Run The Session
augmentedRealitySession.run(configuration, options: [.resetTracking, .removeExistingAnchors])
augmentedRealityView.automaticallyUpdatesLighting = true
}
The above example simple creates a boundingBox from the non-detected ARReferenceObject and places it 0.5m down from and 0.5meter away from the Camera which yields something like this:
You would of course need to handle the position of the boundBox initially, as well as hoe to handle the removal of the boundingBox 'indicator'.
The method below simply shows a boundBox when the actual object is detected e.g:
//--------------------------
// MARK: - ARSCNViewDelegate
//--------------------------
extension ViewController: ARSCNViewDelegate{
func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
//1. Check We Have A Valid ARObject Anchor
guard let objectAnchor = anchor as? ARObjectAnchor else { return }
//2. Create A Bounding Box Around Our Object
let scale = CGFloat(objectAnchor.referenceObject.scale.x)
let boundingBoxNode = BlackMirrorzBoundingBox(points: objectAnchor.referenceObject.rawFeaturePoints.points, scale: scale)
node.addChildNode(boundingBoxNode)
}
}
Which yields something like this:
In regard to the detection timer, there is an example in the Apple Sample Code, which displays how long it takes to detect the model.
In its crudest form (not accounting for milliseconds) you can do something like so:
Firstly create A Timer and a var to store the detection time e.g:
var detectionTimer = Timer()
var detectionTime: Int = 0
Then when you run your ARSessionConfiguration initialise the timer e.g:
/// Starts The Detection Timer
func startDetectionTimer(){
detectionTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(logDetectionTime), userInfo: nil, repeats: true)
}
/// Increments The Total Detection Time Before The ARReference Object Is Detected
#objc func logDetectionTime(){
detectionTime += 1
}
Then when an ARReferenceObject has been detected invalidate the timer and log the time e.g:
//--------------------------
// MARK: - ARSCNViewDelegate
//--------------------------
extension ViewController: ARSCNViewDelegate{
func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
//1. Check We Have A Valid ARObject Anchor
guard let _ = anchor as? ARObjectAnchor else { return }
//2. Stop The Timer
detectionTimer.invalidate()
//3. Log The Detection Time
print("Total Detection Time = \(detectionTime) Seconds")
//4. Reset The Detection Time
detectionTime = 0
}
}
This should be more than enough to get your started...
And please note, that this example doesn't provide a boundingBox when scanning an object (look at the Apple Sample Code for that), it provides one based on an existing ARReferenceObject which is implied in your question (assuming I interpreted it correctly).
Need to move to current location in Esri Map when user clicked on current location button. I try to find out but not able to find anything about it for Esri map
I do following code but it is not working
//MARK:
//MARK: current location button clicked
func btnCurLoc_Clicked(_ sender:UIButton)
{
arcGISMapView.locationDisplay.startDataSource()
}
If you want the map to automatically zoom to the current location you need to also set the autopan modeon the locationDisplay
to one of the options here
The most basic centering one is AGSLocationDisplayAutoPanModeRecenter.
swift 4 and Esri ios SDK 100.1 examples;
func locationOpen(){
self.mapView.locationDisplay.start { _ in
let x:Double = (self.mapView.locationDisplay.mapLocation?.x)!
let y:Double = (self.mapView.locationDisplay.mapLocation?.y)!
DispatchQueue.main.async {
if (self.mapView.locationDisplay.started == false)
{
// permission location
}
else
{ // zoom to geometry
self.mapView.setViewpointCenter(AGSPoint(x: x, y: y, spatialReference: AGSSpatialReference.webMercator()), scale: self.mapView.mapScale, completion: nil)
}
}
}
}