Windows Graphics Documentation

MSDN Sample Code

MR Spatial Anchors Sample Code

This sample demonstrates how to use Spatial Anchors in Mixed Reality applications on Windows. Spatial Anchors allow you to persist the location of virtual objects in the real world, ensuring they stay in place across sessions and devices.

Sample Overview

Technology: DirectX, Mixed Reality API

Platform: Windows Mixed Reality

Purpose: To illustrate the creation, saving, and loading of Spatial Anchors, enabling persistent AR experiences.

Key Features:

  • Capturing current environment state for anchor creation.
  • Saving anchors to a cloud service.
  • Retrieving saved anchors.
  • Anchoring virtual content to real-world locations.

Code Snippet

Below is a simplified C++ code snippet showcasing the core logic for creating and saving a spatial anchor. For the full implementation, please refer to the downloadable project.


#include <windows.h>
#include <SpatialAudioClient.h> // Example include, actual headers will vary
#include <SpatialAnchorApi.h> // Example include

// Assume 'spatialAnchorManager' and 'anchorProperties' are initialized elsewhere

HRESULT CreateAndSaveAnchor(
    SpatialAnchorManager* spatialAnchorManager,
    const AnchorProperties& anchorProperties,
    const GUID& anchorId)
{
    SpatialAnchor* pAnchor = nullptr;
    HRESULT hr = spatialAnchorManager->CreateAnchor(&anchorProperties, &pAnchor);

    if (SUCCEEDED(hr) && pAnchor)
    {
        // Set custom properties if needed
        // pAnchor->SetStringValue(L"ObjectName", L"MyVirtualCube");

        // Save the anchor to the cloud
        hr = spatialAnchorManager->SaveAnchor(pAnchor, anchorId);

        if (SUCCEEDED(hr))
        {
            // Anchor successfully created and saved
            // You can now associate your virtual content with this anchor
            // For example: Attach a 3D model to 'pAnchor'
        }

        pAnchor->Release(); // Release the anchor object
    }

    return hr;
}

// Function to retrieve an anchor
HRESULT LoadAnchor(
    SpatialAnchorManager* spatialAnchorManager,
    const GUID& anchorId)
{
    SpatialAnchor* pAnchor = nullptr;
    HRESULT hr = spatialAnchorManager->GetAnchor(anchorId, &pAnchor);

    if (SUCCEEDED(hr) && pAnchor)
    {
        // Anchor loaded successfully. You can now use 'pAnchor'
        // to position virtual content.
        // For example: Get the transform of the anchor
        // SpatialGraphCoordinateSystem* pCoordinateSystem;
        // HRESULT hrTransform = pAnchor->GetCoordinateSystem(&pCoordinateSystem);

        pAnchor->Release();
    }

    return hr;
}
            

This sample provides a solid foundation for building mixed reality experiences with persistent anchors. Explore the full project to understand event handling, error management, and advanced features.

Download Sample Project (ZIP)