### Clone ARCore Android SDK Sample Project Source: https://developers.google.com/ar/develop/java/depth/quickstart This command clones the ARCore Android SDK repository, which contains sample projects including one that demonstrates the Depth API. Ensure you have Git installed to use this command. ```bash git clone https://github.com/google-ar/arcore-android-sdk.git ``` -------------------------------- ### Check and Request Google Play Services for AR Installation (Kotlin & Java) Source: https://developers.google.com/ar/develop/java/enable-arcore This snippet shows how to use `ArCoreApk.requestInstall()` to verify the installation status of Google Play Services for AR. It handles the cases where the service is already installed, needs to be installed, or the user declines installation, ensuring a compatible ARCore session can be initialized. ```kotlin import com.google.ar.core.ArCoreApk import com.google.ar.core.ArCoreApk.InstallStatus import com.google.ar.core.Session import com.google.ar.core.exceptions.UnavailableUserDeclinedInstallationException import android.app.Activity import android.widget.Toast // requestInstall(Activity, true) will triggers installation of // Google Play Services for AR if necessary. var mUserRequestedInstall = true // Assume mSession is a nullable Session object // Assume this code is within an Activity context fun onResume(activity: Activity) { // ... otheronResume logic ... // Ensure that Google Play Services for AR and ARCore device profile data are // installed and up to date. try { // Check if session is already created // if (mSession == null) { when (ArCoreApk.getInstance().requestInstall(activity, mUserRequestedInstall)) { InstallStatus.INSTALLED -> { // Success: Safe to create the AR session. // mSession = Session(activity) } InstallStatus.INSTALL_REQUESTED -> { // When this method returns `INSTALL_REQUESTED`: // 1. ARCore pauses this activity. // 2. ARCore prompts the user to install or update Google Play // Services for AR (market://details?id=com.google.ar.core). // 3. ARCore downloads the latest device profile data. // 4. ARCore resumes this activity. The next invocation of // requestInstall() will either return `INSTALLED` or throw an // exception if the installation or update did not succeed. mUserRequestedInstall = false return } } // } } catch (e: UnavailableUserDeclinedInstallationException) { // Display an appropriate message to the user and return gracefully. Toast.makeText(activity, "TODO: handle exception " + e, Toast.LENGTH_LONG) .show() return } catch (e: Throwable) { // Handle other potential exceptions during session creation // Log.e(TAG, "Failed to create AR session", e) // mSession remains null, since session creation has failed. return } // ... rest of onResume logic ... } ``` ```java import com.google.ar.core.ArCoreApk; import com.google.ar.core.ArCoreApk.InstallStatus; import com.google.ar.core.Session; import com.google.ar.core.exceptions.UnavailableUserDeclinedInstallationException; import android.app.Activity; import android.widget.Toast; // requestInstall(Activity, true) will trigger installation of // Google Play Services for AR if necessary. private boolean mUserRequestedInstall = true; // Assume mSession is a Session object that can be null // Assume this code is within an Activity context @Override protected void onResume() { super.onResume(); // ... other onResume logic ... // Ensure that Google Play Services for AR and ARCore device profile data are // installed and up to date. try { // Check if session is already created // if (mSession == null) { switch (ArCoreApk.getInstance().requestInstall(this, mUserRequestedInstall)) { case INSTALLED: // Success: Safe to create the AR session. // mSession = new Session(this); break; case INSTALL_REQUESTED: // When this method returns `INSTALL_REQUESTED`: // 1. ARCore pauses this activity. // 2. ARCore prompts the user to install or update Google Play // Services for AR (market://details?id=com.google.ar.core). // 3. ARCore downloads the latest device profile data. // 4. ARCore resumes this activity. The next invocation of // requestInstall() will either return `INSTALLED` or throw an // exception if the installation or update did not succeed. mUserRequestedInstall = false; return; } // } } catch (UnavailableUserDeclinedInstallationException e) { // Display an appropriate message to the user and return gracefully. Toast.makeText(this, "TODO: handle exception " + e, Toast.LENGTH_LONG) .show(); return; } catch (Throwable e) { // Handle other potential exceptions during session creation // Log.e(TAG, "Failed to create AR session", e); return; // mSession remains null, since session creation has failed. } // ... rest of onResume logic ... } ``` -------------------------------- ### Configure ARRaycastManager in AR Foundation (4.x, 5.x, 6.x) Source: https://developers.google.com/ar/develop/unity-arf/instant-placement/developer-guide Steps to add the AR Session Origin, AR Session, and AR Raycast Manager components to your Unity scene for AR Foundation versions 4.x, 5.x, and 6.x. This setup enables Instant Placement functionality. ```csharp // AR Foundation 4.x // 1. Add the predefined game objects AR Session Origin and AR Session. // 2. Add the AR Raycast Manager component into the AR Session Origin game object. // AR Foundation 5.x // 1. Add the predefined game objects XR Origin and AR Session. // 2. Add the AR Raycast Manager component into the XR Origin game object. // AR Foundation 6.x // 1. Add the predefined game objects XR Origin and AR Session. // 2. Add the AR Raycast Manager component into the XR Origin game object. // When Raycast Prefab is not null, ARRaycastManager will instantiate the prefab and automatically sync its pose with the pose of ARRaycast. ``` -------------------------------- ### Start AR Mode with Camera Capture Session Callbacks Source: https://developers.google.com/ar/develop/java/camera-sharing_hl=de This snippet demonstrates how to start AR mode by configuring camera capture sessions and resuming the ARCore session. It includes callbacks for session state changes and capture events. This is crucial for initializing ARCore and handling camera frame processing. ```java CameraCaptureSession.StateCallback cameraSessionStateCallback = new CameraCaptureSession.StateCallback() { // Called when ARCore first configures the camera capture session after // initializing the app, and again each time the activity resumes. @Override public void onConfigured(@NonNull CameraCaptureSession session) { captureSession = session; setRepeatingCaptureRequest(); } @Override public void onActive(@NonNull CameraCaptureSession session) { if (arMode && !arcoreActive) { resumeARCore(); } } }; // A repeating camera capture session capture callback. CameraCaptureSession.CaptureCallback cameraCaptureCallback = new CameraCaptureSession.CaptureCallback() { @Override public void onCaptureCompleted(…) { shouldUpdateSurfaceTexture.set(true); } }; void setRepeatingCaptureRequest() { captureSession.setRepeatingRequest( previewCaptureRequestBuilder.build(), cameraCaptureCallback, backgroundHandler); } void resumeARCore() { // Resume ARCore. sharedSession.resume(); arcoreActive = true; // Set the capture session callback while in AR mode. sharedCamera.setCaptureCallback(cameraCaptureCallback, backgroundHandler); } ``` -------------------------------- ### Check and Request Google Play Services for AR Installation (C/C++) Source: https://developers.google.com/ar/develop/c/enable-arcore This C/C++ code snippet demonstrates how to use `ArCoreApk_requestInstall()` to check if Google Play Services for AR is installed and up-to-date. It handles the installation process, including user prompts and background downloads, before proceeding to create an ARCore session. This is crucial for both 'AR Required' and 'AR Optional' applications. ```cpp // Tracks if an installation request has already been triggered. bool install_requested_; void nativeOnCreate() { // Do other setup here. install_requested_ = false; } void nativeOnResume(JNIEnv env, jobject activity) { if (ar_session_ == null) { bool user_requested_install = !install_requested_; ArInstallStatus install_status; // Ensure that Google Play Services for AR and ARCore device profile data are // installed and up to date. ArStatus error = ArCoreApk_requestInstall( env, activity, user_requested_install, &install_status); if (error != AR_SUCCESS) { // Inform user of error. return; } switch (install_status) { case AR_INSTALL_STATUS_INSTALLED: break; case AR_INSTALL_STATUS_INSTALL_REQUESTED: // When this method returns AR_INSTALL_STATUS_INSTALL_REQUESTED: // 1. This activity will be paused. // 2. The user is prompted to install or update Google Play // Services for AR (market://details?id=com.google.ar.core). // 3. ARCore downloads the latest device profile data. // 4. This activity is resumed. The next invocation of // ArCoreApk_requestInstall() will either return // AR_INSTALL_STATUS_INSTALLED or throw an exception if the // installation or update did not succeed. install_requested_ = true; return; } // Request camera permissions. error = ArSession_create(env, context, &ar_session_); if (error != AR_SUCCESS) { // Inform user of error. return; } // Configure the ARCore session. } // Normal onResume behavior. } ``` -------------------------------- ### Verify ARCore Installation and Update Status (Kotlin) Source: https://developers.google.com/ar/develop/java/session-config This Kotlin code snippet performs the same function as the Java version: verifying ARCore's installation and update status. It uses Kotlin's `when` expression for cleaner conditional logic. The snippet handles different availability states, including requesting installation or updates, and returns a boolean indicating ARCore's readiness. ```kotlin fun isARCoreSupportedAndUpToDate(): Boolean { return when (ArCoreApk.getInstance().checkAvailability(this)) { Availability.SUPPORTED_INSTALLED -> true Availability.SUPPORTED_APK_TOO_OLD, Availability.SUPPORTED_NOT_INSTALLED -> { try { // Request ARCore installation or update if needed. when (ArCoreApk.getInstance().requestInstall(this, true)) { InstallStatus.INSTALL_REQUESTED -> { Log.i(TAG, "ARCore installation requested.") false } InstallStatus.INSTALLED -> true } } catch (e: UnavailableException) { Log.e(TAG, "ARCore not installed", e) false } } Availability.UNSUPPORTED_DEVICE_NOT_CAPABLE -> // This device is not supported for AR. false Availability.UNKNOWN_CHECKING -> { // ARCore is checking the availability with a remote query. // This function should be called again after waiting 200 ms to determine the query result. } Availability.UNKNOWN_ERROR, Availability.UNKNOWN_TIMED_OUT -> { // There was an error checking for AR availability. This may be due to the device being offline. // Handle the error appropriately. } } } ``` -------------------------------- ### Start AR Mode with Camera Capture Session Callbacks (Kotlin) Source: https://developers.google.com/ar/develop/java/camera-sharing_hl=de This snippet shows how to initiate AR mode using Kotlin, focusing on camera capture session configuration and ARCore session resumption. It utilizes object expressions for callbacks and lambda functions for concise code. This is essential for ARCore initialization and camera frame handling. ```kotlin val cameraSessionStateCallback = object : CameraCaptureSession.StateCallback() { // Called when ARCore first configures the camera capture session after // initializing the app, and again each time the activity resumes. override fun onConfigured(session: CameraCaptureSession) { captureSession = session setRepeatingCaptureRequest() } override fun onActive(session: CameraCaptureSession) { if (arMode && !arcoreActive) { resumeARCore() } } } val cameraCaptureCallback = object : CameraCaptureSession.CaptureCallback() { override fun onCaptureCompleted( session: CameraCaptureSession, request: CaptureRequest, result: TotalCaptureResult ) { shouldUpdateSurfaceTexture.set(true); } } fun setRepeatingCaptureRequest() { captureSession.setRepeatingRequest( previewCaptureRequestBuilder.build(), cameraCaptureCallback, backgroundHandler ) } fun resumeARCore() { // Resume ARCore. sharedSession.resume() arcoreActive = true // Set the capture session callback while in AR mode. sharedCamera.setCaptureCallback(cameraCaptureCallback, backgroundHandler) } ``` -------------------------------- ### Check Tracking State and Get Geospatial Pose Source: https://developers.google.com/ar/develop/java/geospatial/obtain-device-pose This snippet demonstrates how to check if the Earth's tracking state is 'TRACKING' before calling `getCameraGeospatialPose()` to obtain the device's geospatial pose. It includes examples for both Java and Kotlin. ```APIDOC ## GET /websites/developers_google_ar_develop ### Description Retrieves the geospatial pose of the device's camera, including location, altitude, and orientation, when the Earth's tracking state is active. This is crucial for AR applications that rely on real-world positioning. ### Method GET ### Endpoint /websites/developers_google_ar_develop ### Parameters #### Query Parameters - **earth** (object) - Required - The Earth object managing ARCore's geospatial features. - **trackingState** (enum) - Required - The current tracking state of the Earth object. Must be `TrackingState.TRACKING`. #### Request Body None ### Request Example ```java if (earth != null && earth.getTrackingState() == TrackingState.TRACKING) { GeospatialPose cameraGeospatialPose = earth.getCameraGeospatialPose(); // Process cameraGeospatialPose } ``` ```kotlin if (earth.trackingState == TrackingState.TRACKING) { val cameraGeospatialPose = earth.cameraGeospatialPose // Process cameraGeospatialPose } ``` ### Response #### Success Response (200) - **GeospatialPose** (object) - An object containing the device's geospatial information (latitude, longitude, altitude, orientation). - **latitude** (double) - The device's latitude. - **longitude** (double) - The device's longitude. - **altitude** (double) - The device's altitude above mean sea level. - **orientation** (Quaternion) - The device's orientation in the EUS coordinate system. - **yawAccuracy** (double) - The accuracy estimate for the yaw angle in degrees. #### Response Example ```json { "latitude": 37.4220, "longitude": -122.0841, "altitude": 100.0, "orientation": { "w": 0.707, "x": 0.0, "y": 0.707, "z": 0.0 }, "yawAccuracy": 10.5 } ``` #### Error Response (400) - **error** (string) - Description of the error if tracking is not active or another issue occurs. #### Error Response Example ```json { "error": "Earth tracking is not in TRACKING state." } ``` ``` -------------------------------- ### Open ARCore Sample Project in Android Studio (Kotlin) Source: https://developers.google.com/ar/develop/java/quickstart Instructions for opening the 'hello_ar_kotlin' sample project within Android Studio after cloning the ARCore SDK. This allows you to build and run the Kotlin-based AR sample. ```java File -> Open -> navigate to arcore-android-sdk/samples/hello_ar_kotlin -> Open ``` -------------------------------- ### Extract Custom Data Bytes and Decode (Java & Kotlin) Source: https://developers.google.com/ar/develop/java/recording-and-playback/custom-data-track Extracts the raw byte data from `TrackData` objects and decodes it. This example demonstrates how to get the `ByteBuffer` containing the custom data and then use it to retrieve specific values, such as a 'Lamp' enum, by indexing into the byte array. ```java // Extract the bytes of custom data from the list of track data. for (TrackData trackData : trackDataList) { ByteBuffer bytes = trackData.getData(); Lamp lamp = Lamp.values()[bytes.get()]; // this is the lamp! } ``` ```kotlin // Extract the bytes of custom data from the list of track data. for (trackData in trackDataList) { val bytes = trackData.data val lamp = Lamp.values()[bytes.get().toInt()] // this is the lamp! } ``` -------------------------------- ### Next Steps Source: https://developers.google.com/ar/develop/java/geospatial/enable Learn how to obtain the device camera's Geospatial pose and check VPS availability at a given location. ```APIDOC ## What's next * Obtain the device camera's Geospatial pose to determine the exact location of the user's device in the real world. * Check VPS availability at a device's given location. ``` -------------------------------- ### Open ARCore Sample Project in Android Studio (Java) Source: https://developers.google.com/ar/develop/java/quickstart Instructions for opening the 'hello_ar_java' sample project within Android Studio after cloning the ARCore SDK. This allows you to build and run the Java-based AR sample. ```java File -> Open -> navigate to arcore-android-sdk/samples/hello_ar_java -> Open ``` -------------------------------- ### Get Detected Faces (Java & Kotlin) Source: https://developers.google.com/ar/develop/java/augmented-faces/developer-guide Retrieves all detected faces from the ARCore session. This is the first step to accessing face-related tracking information. ARCore's face detection performs best with upright faces. ```java // ARCore's face detection works best on upright faces, relative to gravity. Collection faces = session.getAllTrackables(AugmentedFace.class); ``` ```kotlin // ARCore's face detection works best on upright faces, relative to gravity. val faces = session.getAllTrackables(AugmentedFace::class.java) ``` -------------------------------- ### Check Google Play Services for AR Installation (Unity) Source: https://developers.google.com/ar/develop/unity-arf/enable-arcore Use `ARSession.Install()` coroutine before creating an ARCore session to check for and prompt installation/update of Google Play Services for AR and ARCore device profile data. ```csharp ARSession.Install() coroutine ``` -------------------------------- ### Attach 3D Objects to Face Regions (Swift) Source: https://developers.google.com/ar/develop/ios/augmented-faces/developer-guide Shows how to attach 3D objects to specific regions of a detected face using ARCore's GARAugmentedFace transforms. This example demonstrates attaching a sphere to the nose by updating the node's world transform in each frame. ```swift // Create node and add to scene let node = SCNNode(geometry: SCNSphere(radius: .02)) sceneView.rootNode.addChild(node) // Every frame updates the node's position node.simdWorldTransform = session.currentFrame.face.transform(for: .nose) ``` -------------------------------- ### Check VPS Availability with ARCore API (C++) Source: https://developers.google.com/ar/develop/c/geospatial/check-vps-availability This snippet demonstrates how to check for VPS availability using the ARCore API in C++. It involves enabling the ARCore API, creating an `ArVpsAvailabilityFuture`, and then polling the future's state or using a callback to determine VPS availability. The future can also be canceled. This is useful even if VPS is not available, as the API falls back to GPS. ```c++ { // Enable the ARCore API ArSession_checkVpsAvailabilityAsync(session, &vpsAvailabilityFuture); // Poll the ArFuture state or use a callback ArFuture_getState(vpsAvailabilityFuture); // Cancel the ArFuture ArFuture_cancel(vpsAvailabilityFuture); } ``` -------------------------------- ### Acquire Raw Depth and Confidence Images (Java) Source: https://developers.google.com/ar/develop/java/depth/raw-depth Demonstrates how to acquire raw depth images (16-bit) and their corresponding confidence images using the Raw Depth API. These images are essential for applications like 3D reconstruction and measurement. The API does not require dedicated hardware depth sensors. ```Java DepthImage depthImage = frame.acquireRawDepthImage16Bits(); Image depthConfidenceImage = frame.acquireRawDepthConfidenceImage(); ``` -------------------------------- ### Check ARCore Installation and Support Source: https://developers.google.com/ar/develop/java/camera-sharing Verifies if ARCore is installed and up-to-date on the device. If not installed or outdated, it prompts the user to install or update ARCore. This is crucial for ensuring AR functionality. ```java boolean isARCoreSupportedAndUpToDate() { // Make sure that ARCore is installed and supported on this device. ArCoreApk.Availability availability = ArCoreApk.getInstance().checkAvailability(this); switch (availability) { case SUPPORTED_INSTALLED: return true; case SUPPORTED_APK_TOO_OLD: case SUPPORTED_NOT_INSTALLED: // Requests an ARCore installation or updates ARCore if needed. ArCoreApk.InstallStatus installStatus = ArCoreApk.getInstance().requestInstall(this, userRequestedInstall); switch (installStatus) { case INSTALL_REQUESTED: return false; case INSTALLED: return true; } return false; default: // Handle the error. For example, show the user a snackbar that tells them // ARCore is not supported on their device. return false; } } ``` ```kotlin // Determine ARCore installation status. // Requests an ARCore installation or updates ARCore if needed. fun isARCoreSupportedAndUpToDate(): Boolean { when (ArCoreApk.getInstance().checkAvailability(this)) { Availability.SUPPORTED_INSTALLED -> return true Availability.SUPPORTED_APK_TOO_OLD, Availability.SUPPORTED_NOT_INSTALLED -> { when(ArCoreApk.getInstance().requestInstall(this, userRequestedInstall)) { InstallStatus.INSTALLED -> return true else -> return false } } else -> { // Handle the error. For example, show the user a snackbar that tells them // ARCore is not supported on their device. return false } } } ``` -------------------------------- ### Comprobar y solicitar instalación de ARCore (Java) Source: https://developers.google.com/ar/develop/c/enable-arcore_hl=es-419 Este snippet muestra cómo comprobar la disponibilidad de ARCore y solicitar su instalación si no está presente. Es crucial para asegurar que la aplicación pueda ejecutar funcionalidades de Realidad Aumentada. Requiere la biblioteca ARCore. ```java import com.google.ar.core.ArCoreApk; // ... dentro de una Activity o Context private void checkArCore() { ArCoreApk.Availability availability = ArCoreApk.checkAvailability(this); if (availability.isTransient()) return; if (!availability.isSupported()) { ArCoreApk.requestInstall(this, true); return; } // ARCore está disponible y soportado } ``` -------------------------------- ### Verify ARCore Installation and Update Status (Java) Source: https://developers.google.com/ar/develop/java/session-config This Java code snippet checks if ARCore is installed and up-to-date on the device. It handles cases where ARCore is supported but needs installation or an update, requesting the installation if necessary. If the device is not capable of AR, it returns false. The function returns a boolean indicating whether ARCore is supported and installed. ```java private boolean isARCoreSupportedAndUpToDate() { ArCoreApk.Availability availability = ArCoreApk.getInstance().checkAvailability(this); switch (availability) { case SUPPORTED_INSTALLED: return true; case SUPPORTED_APK_TOO_OLD: case SUPPORTED_NOT_INSTALLED: try { // Request ARCore installation or update if needed. ArCoreApk.InstallStatus installStatus = ArCoreApk.getInstance().requestInstall(this, true); switch (installStatus) { case INSTALL_REQUESTED: Log.i(TAG, "ARCore installation requested."); return false; case INSTALLED: return true; } } catch (UnavailableException e) { Log.e(TAG, "ARCore not installed", e); } return false; case UNSUPPORTED_DEVICE_NOT_CAPABLE: // This device is not supported for AR. return false; case UNKNOWN_CHECKING: // ARCore is checking the availability with a remote query. // This function should be called again after waiting 200 ms to determine the query result. case UNKNOWN_ERROR: case UNKNOWN_TIMED_OUT: // There was an error checking for AR availability. This may be due to the device being offline. // Handle the error appropriately. } } ``` -------------------------------- ### Check and Request Google Play Services for AR Installation (Kotlin/Java) Source: https://developers.google.com/ar/develop/java/enable-arcore_hl=it This snippet demonstrates how to use `ArCoreApk.requestInstall()` to ensure Google Play Services for AR is installed and up-to-date before creating an ARCore session. It handles the `INSTALLED` and `INSTALL_REQUESTED` statuses, as well as `UnavailableUserDeclinedInstallationException`. ```kotlin var mUserRequestedInstall = true override fun onResume() { super.onResume() // Check camera permission. … // Ensure that Google Play Services for AR and ARCore device profile data are // installed and up to date. try { if (mSession == null) { when (ArCoreApk.getInstance().requestInstall(this, mUserRequestedInstall)) { ArCoreApk.InstallStatus.INSTALLED -> { // Success: Safe to create the AR session. mSession = Session(this) } ArCoreApk.InstallStatus.INSTALL_REQUESTED -> { // When this method returns `INSTALL_REQUESTED`: // 1. ARCore pauses this activity. // 2. ARCore prompts the user to install or update Google Play // Services for AR (market://details?id=com.google.ar.core). // 3. ARCore downloads the latest device profile data. // 4. ARCore resumes this activity. The next invocation of // requestInstall() will either return `INSTALLED` or throw an // exception if the installation or update did not succeed. mUserRequestedInstall = false return } } } } catch (e: UnavailableUserDeclinedInstallationException) { // Display an appropriate message to the user and return gracefully. Toast.makeText(this, "TODO: handle exception " + e, Toast.LENGTH_LONG) .show() return } catch (…) { … return // mSession remains null, since session creation has failed. } … ``` ```java // requestInstall(Activity, true) will trigger installation of // Google Play Services for AR if necessary. private boolean mUserRequestedInstall = true; @Override protected void onResume() { super.onResume(); // Check camera permission. … // Ensure that Google Play Services for AR and ARCore device profile data are // installed and up to date. try { if (mSession == null) { switch (ArCoreApk.getInstance().requestInstall(this, mUserRequestedInstall)) { case INSTALLED: // Success: Safe to create the AR session. mSession = new Session(this); break; case INSTALL_REQUESTED: // When this method returns `INSTALL_REQUESTED`: // 1. ARCore pauses this activity. // 2. ARCore prompts the user to install or update Google Play // Services for AR (market://details?id=com.google.ar.core). // 3. ARCore downloads the latest device profile data. // 4. ARCore resumes this activity. The next invocation of // requestInstall() will either return `INSTALLED` or throw an // exception if the installation or update did not succeed. mUserRequestedInstall = false; return; } } } catch (UnavailableUserDeclinedInstallationException e) { // Display an appropriate message to the user and return gracefully. Toast.makeText(this, "TODO: handle exception " + e, Toast.LENGTH_LONG) .show(); return; } catch (…) { … return; // mSession remains null, since session creation has failed. } … ``` -------------------------------- ### Enabling Scene Viewer with model-viewer Component (HTML) Source: https://developers.google.com/ar/develop/java/scene-viewer This HTML snippet demonstrates how to integrate the `` web component to enable Scene Viewer functionality. By including the `ar` attribute and specifying `ar-modes`, you allow users to launch AR experiences. The example shows how to set an alternative text and the source of the 3D model. ```html ``` -------------------------------- ### Check ARCore Availability and Request Install in Instant Apps (Java) Source: https://developers.google.com/ar/develop/c/instant-app This Java code snippet demonstrates how to check if Google Play Services for AR is installed and request its installation within an AR-enabled Play Instant App. This is crucial because Google Play does not automatically manage ARCore installation for instant apps. ```java import com.google.ar.core.ArCoreApk; // ... inside your Activity or Fragment private void checkArCoreAvailability() { ArCoreApk.Availability availability = ArCoreApk.checkAvailability(this); if (availability.isTransient()) { // The user has requested the app to be installed, and it is in the process of being installed. // This is a transient state, and the user should be informed that the app is still being installed. } else if (availability.isUnsupported()) { // The device does not support ARCore. // Inform the user that ARCore is not supported on their device. } else if (availability.isInstalled()) { // ARCore is installed and ready to use. // Proceed with AR functionality. } else { // ARCore is not installed. Request installation. try { ArCoreApk.requestInstall(this, true); } catch (ArCoreApk.InstallException e) { // Handle the exception, e.g., inform the user about the installation failure. e.printStackTrace(); } } } ``` -------------------------------- ### Extraer bibliotecas nativas de ARCore (C/C++) Source: https://developers.google.com/ar/develop/c/enable-arcore_hl=es Instrucciones para extraer bibliotecas nativas de ARCore para proyectos C/C++. Esto es necesario si estás desarrollando funcionalidades de AR de bajo nivel o integrando ARCore en un motor de juegos. ```bash unzip ARCore_native_libraries.zip -d extracted_libs ``` -------------------------------- ### Enable Cloud Anchor Capabilities in ARCore Session Configuration (C) Source: https://developers.google.com/ar/develop/c/cloud-anchors/developer-guide This C code snippet demonstrates how to enable Cloud Anchor mode within an ARCore session configuration. It involves creating an ARCore session, getting its configuration, setting the Cloud Anchor mode to enabled, and then applying the updated configuration back to the session. Ensure the ARCore API is enabled in your application before using this. ```c ArSession* session = NULL; CHECK(ArSession_create(env, context, &session) == AR_SUCCESS); // Create a session config. ArConfig* config = NULL; ArConfig_create(session, &config); ArSession_getConfig(session, config); // Enable Cloud Anchor mode. ArConfig_setCloudAnchorMode(session, config, AR_CLOUD_ANCHOR_MODE_ENABLED); // Configure the session. ArSession_configure(session, config); ArConfig_destroy(config); ``` -------------------------------- ### Scene Viewer Intent Parameters Source: https://developers.google.com/ar/develop/scene-viewer Details on supported intent parameters for launching Scene Viewer, including their allowed values and descriptions. ```APIDOC ## GET /websites/developers_google_ar_develop ### Description Provides a comprehensive list of supported intent parameters for launching Scene Viewer, detailing their purpose, allowed values, and specific usage notes. ### Method GET ### Endpoint N/A (Documentation of parameters) ### Parameters #### Query Parameters - **browser_fallback_url** (string, required for HTML intents) - A valid URL. Used in web-based implementations when Google Play Services for AR is not present or up to date. - **mode** (string, optional) - Allowed values: `ar_only`. Forces Scene Viewer to launch in a native AR view, hiding UI for switching to 3D viewer. - **ar_preferred** (boolean, optional) - Scene Viewer launches in AR native mode, offering users the option to switch between AR and 3D modes. - **link** (string, optional) - A valid URL for an external webpage. A button will be surfaced in the UI that intents to this URL when clicked. Use with care, ensuring an intent handler is present. - **title** (string, optional) - A name for the model. If present, it will be displayed in the UI. Supports HTML styling and url-escaping. Truncated after 60 characters. - **sound** (string, optional) - A URL to a looping audio track synchronized with the first animation embedded in a glTF file. Provided alongside a glTF with matching animation length. - **resizable** (boolean, optional) - Allowed values: `true` (default), `false`. Controls whether users can scale the model in AR experience. - **disable_occlusion** (boolean, optional) - Allowed values: `false` (default), `true`. When `true`, objects in the scene always appear in front of real-world objects. ### Response #### Success Response (200) Documentation detailing the Scene Viewer intent parameters. #### Response Example (No direct response body, documentation content) ``` -------------------------------- ### Verify ARCore Installation and Update Status (C++) Source: https://developers.google.com/ar/develop/c/session-config Checks if ARCore is installed and up-to-date on the device. If not, it attempts to request an installation or upgrade. This function returns a boolean indicating the availability status and handles different ARCore availability states, including device capability checks and remote query statuses. ```c++ /* * Check if ARCore is currently usable, i.e. whether ARCore is supported and * up to date. */ int32_t is_arcore_supported_and_up_to_date(void* env, void* context) { ArAvailability availability; ArCoreApk_checkAvailability(env, context, &availability); switch (availability) { case AR_AVAILABILITY_SUPPORTED_INSTALLED: return true; case AR_AVAILABILITY_SUPPORTED_APK_TOO_OLD: case AR_AVAILABILITY_SUPPORTED_NOT_INSTALLED: { ArInstallStatus install_status; // ArCoreApk_requestInstall is processed asynchronously. CHECK(ArCoreApk_requestInstall(env, context, true, &install_status) == AR_SUCCESS); return false; } case AR_AVAILABILITY_UNSUPPORTED_DEVICE_NOT_CAPABLE: // This device is not supported for AR. return false; case AR_AVAILABILITY_UNKNOWN_CHECKING: // ARCore is checking the availability with a remote query. // This function should be called again after waiting 200 ms // to determine the query result. handle_check_later(); return false; case AR_AVAILABILITY_UNKNOWN_ERROR: case AR_AVAILABILITY_UNKNOWN_TIMED_OUT: // There was an error checking for AR availability. // This may be due to the device being offline. // Handle the error appropriately. handle_unknown_error(); return false; default: // All enum cases have been handled. return false; } } ``` -------------------------------- ### Start and Stop AR Recording using Recording & Playback API Source: https://developers.google.com/ar/develop/unity-arf/recording-and-playback/developer-guide_hl=pl This snippet demonstrates how to initiate and terminate the recording of AR sessions. It requires configuring a session and providing an MP4 URI for saving the recording. The `ARRecordingManager.StartRecording()` method begins the process, while `ARRecordingManager.StopRecording()` halts it. Ensure the AR session is properly initialized before calling these methods. ```csharp ARRecordingManager.StartRecording(mp4Uri); // ... recording in progress ... ARRecordingManager.StopRecording(); ``` -------------------------------- ### AR UX Guidance and Fallback Implementation Source: https://developers.google.com/ar/develop/scene-viewer Provides UX recommendations for AR experiences, including the 'View in your space' call to action, and demonstrates a JavaScript fallback mechanism for devices without Google Play Services for AR. ```APIDOC ## UX Guidance for AR Experiences ### Description Provides recommendations for creating a seamless user experience for AR applications, focusing on clear calls to action and handling potential device limitations. ### Key Recommendations * **Call to Action:** For AR experiences, the visible call to action should clearly indicate that the user is about to enter an immersive environment. The recommended call to action is **"View in your space"**. * **Fallback Mechanism:** Users may not have Google Play Services for AR installed. The following code snippet demonstrates a starting point for handling this fallback scenario using ``. ### Fallback Code Example ```javascript // Check whether this is an Android device. const isAndroid = /android/i.test(navigator.userAgent); // This fallback URL is used if the Google app is not installed and up to date. const fallbackUrl = 'https://arvr.google.com/scene-viewer?file=https%3A%2F%2Fstorage.googleapis.com%2Far-answers-in-search-models%2Fstatic%2FTiger%2Fmodel.glb&link=https%3A%2F%2Fgoogle.com&title=Tiger'; // This intent URL triggers Scene Viewer on Android and falls back to // fallbackUrl if the Google app is not installed and up to date. const sceneViewerUrl = 'intent://arvr.google.com/scene-viewer/1.0?file=https://storage.googleapis.com/ar-answers-in-search-models/static/Tiger/model.glb&title=Tiger#Intent;scheme=https;package=com.google.android.googlequicksearchbox;action=android.intent.action.VIEW;S.browser_fallback_url=' + fallbackUrl + ';end;'; // Create a link. var a = document.createElement('a'); a.appendChild(document.createTextNode('Tiger')); // Set the href to the intent URL on Android and the fallback URL // everywhere else. a.href = isAndroid ? sceneViewerUrl : fallbackUrl; // Add the link to the page. document.body.appendChild(a); ``` ``` -------------------------------- ### Configure ARCore Session with API Key in Objective-C Source: https://developers.google.com/ar/develop/ios/geospatial/quickstart This Objective-C code snippet shows how to initialize the GARSession with an API key for making Geospatial API calls. Ensure you replace 'your-api-key' with your actual API key. The bundle identifier can be set to nil if not using a restricted API key. ```objective-c self.garSession = [GARSession sessionWithAPIKey:@"your-api-key" bundleIdentifier:nil error:&error]; ``` -------------------------------- ### Record ARCore Session - C/C++ Source: https://developers.google.com/ar/develop/c/recording-and-playback/developer-guide Configures and starts recording an ARCore session. It requires an AR session object, a recording configuration, and an MP4 dataset URI. Recording starts when the AR session is resumed. Auto-stop on pause can be enabled. Partial sessions can also be recorded by starting recording while the session is running. ```c ArRecordingConfig* recording_config = nullptr; ArRecordingConfig_create(ar_session, &recording_config); ArRecordingConfig_setMp4DatasetUri(ar_session, recording_config, mp4_dataset_uri); ArRecordingConfig_setAutoStopOnPause(ar_session, recording_config, true); CHECK(ArSession_startRecording(ar_session, recording_config)); // … // Resume ARCore session to start recording. CHECK(ArSession_resume(ar_session)); // … // Recording ends. CHECK(ArSession_pause(ar_session)); ``` -------------------------------- ### Launch Scene Viewer from HTML Source: https://developers.google.com/ar/develop/java/scene-viewer This snippet demonstrates how to launch Scene Viewer from an HTML link using an explicit intent. It specifies the 3D model file and includes a fallback URL for devices that do not support AR. The `scheme`, `package`, and `action` parameters are crucial for the intent to be handled correctly by the Google app. ```html Avocado ``` -------------------------------- ### Instant Placement Wrapper Class (Java & Kotlin) Source: https://developers.google.com/ar/develop/java/instant-placement/developer-guide A wrapper class to hold InstantPlacementPoint state, including previous tracking method and distance to the camera. This helps in managing transitions and reducing sudden visual changes in object size. ```java class WrappedInstantPlacement { public InstantPlacementPoint point; public InstantPlacementPoint.TrackingMethod previousTrackingMethod; public float previousDistanceToCamera; public float scaleFactor = 1.0f; public WrappedInstantPlacement( InstantPlacementPoint point, InstantPlacementPoint.TrackingMethod previousTrackingMethod, float previousDistanceToCamera) { this.point = point; this.previousTrackingMethod = previousTrackingMethod; this.previousDistanceToCamera = previousDistanceToCamera; } } ``` ```kotlin class WrappedInstantPlacement( var point: InstantPlacementPoint, var previousTrackingMethod: InstantPlacementPoint.TrackingMethod, var previousDistanceToCamera: Float, var scaleFactor: Float = 1.0f ) ``` -------------------------------- ### Example Operations Source: https://developers.google.com/ar/develop/cloud-anchors/management-api This section provides examples of common operations using the ARCore Cloud Anchor Management API, including listing, updating, and deleting Cloud Anchors. ```APIDOC ## Example Operations ### List all Cloud Anchors This operation retrieves a list of all Cloud Anchors associated with your project. - **Method:** GET - **Endpoint:** `/cloud-anchors` (Illustrative endpoint, actual endpoint may vary) ### Update a Cloud Anchor’s Time to Live (TTL) This operation allows you to update the TTL of a specific Cloud Anchor to the maximum allowed duration. - **Method:** PUT or PATCH (Illustrative, actual method may vary) - **Endpoint:** `/cloud-anchors/{anchor_id}/ttl` (Illustrative endpoint, actual endpoint may vary) - **Request Body:** - `ttl_duration` (integer) - Required - The new time to live duration in seconds. ### Delete Cloud Anchors This operation allows you to delete Cloud Anchors. Anchors can be deleted individually or in batches. - **Method:** DELETE - **Endpoint:** `/cloud-anchors/{anchor_id}` (for individual deletion) or `/cloud-anchors/batch` (for batch deletion) (Illustrative endpoints, actual endpoints may vary) - **Request Body (for batch deletion):** - `anchor_ids` (array of strings) - Required - A list of anchor IDs to delete. ```