Exemple #1
0
    [DrawGizmo(GizmoType.Active | GizmoType.Pickable)]      // Draw the gizmo if it is not selected and also no parent/ancestor object is selected. The gizmo can be picked in the editor. First argument of method is the type for which the Gizmo will be drawn.
#endif
    private static void RenderARTrackedMarkerGizmo(ARTrackable arTrackable, GizmoType gizmoType)
    {
        if (null == arTrackable || !arTrackable.gameObject.activeInHierarchy)
        {
            // Don't attempt to load inactive or null ARMarkers.
            return;
        }
        bool selected = (gizmoType & GizmoType.Active) != 0;

        // Attempt to load. Might not work out if e.g. for a single marker, pattern hasn't been
        // assigned yet, or for an NFT marker, dataset hasn't been specified.
        if (arTrackable.UID == ARTrackable.NO_ID)
        {
            arTrackable.Load();
        }

        Matrix4x4 pose = arTrackable.gameObject.transform.localToWorldMatrix;

        switch (arTrackable.Type)
        {
        case ARTrackable.TrackableType.Square:
        case ARTrackable.TrackableType.SquareBarcode:
            DrawSingleMarker(arTrackable, pose, selected);
            break;

        case ARTrackable.TrackableType.Multimarker:
            DrawMultiMarker(arTrackable, pose, selected);
            break;

        case ARTrackable.TrackableType.TwoD:
            DrawTwoDMarker(arTrackable, pose, selected);
            break;
        }
    }
    private static void DrawMultiMarker(ARTrackable m, Matrix4x4 mat, bool selected)
    {
        //Sanity check if Patterns are loaded or Marker-UID != -1
        if (m.Patterns == null || m.UID == ARTrackable.NO_ID)
        {
            return;
        }

        for (int i = 0; i < m.Patterns.Length; i++)
        {
            Matrix4x4 mat1 = mat * m.Patterns[i].matrix;

            float pattWidth = m.Patterns[i].width;

            //float d = selected ? 1.0f : 0.0f;

            Vector3 origin = mat1.GetColumn(3);
            Vector3 right  = mat1.GetColumn(0);
            Vector3 up     = mat1.GetColumn(1);

            DrawRectangle(origin, up, right, pattWidth * 0.5f, pattWidth * 0.5f, selected ? MarkerBorderSelected : MarkerBorderUnselected); // Inside border.
            DrawRectangle(origin, up, right, pattWidth, pattWidth, selected ? MarkerBorderSelected : MarkerBorderUnselected);               // Edge.
            DrawRectangle(origin, up, right, pattWidth * 1.05f, pattWidth * 1.05f, selected ? MarkerEdgeSelected : MarkerEdgeUnselected);   // Highlighting.

            float wordUnitSize = pattWidth * 0.02f;
            DrawWord(m.Tag + "(" + i + ")", wordUnitSize, origin - up * (pattWidth * 0.6f + (wordUnitSize * 4)) - right * (pattWidth * 0.525f), up, right * 0.5f);
        }

        //Gizmos.DrawGUITexture(new Rect(origin.x, origin.y, 20, 20), m.MarkerImage);
    }
Exemple #3
0
    // Get the trackable, if any, currently acting as the base.
    public ARTrackable GetBaseTrackable()
    {
        if (baseTrackable != null)
        {
            if (baseTrackable.Visible)
            {
                return(baseTrackable);
            }
            else
            {
                baseTrackable = null;
            }
        }
        foreach (ARTrackable m in trackablesEligibleForBaseTrackable)
        {
            if (m.Visible)
            {
                baseTrackable = m;
                ARController.Log("Trackable " + m.UID + " became base trackable.");
                break;
            }
        }

        return(baseTrackable);
    }
Exemple #4
0
        private void _CreateWorld(Touch touch)
        {
            List <ARHitResult> hitResults = ARFrame.HitTest(touch);

            ARDebug.LogInfo("_DrawARLogo hitResults count {0}", hitResults.Count);
            foreach (ARHitResult singleHit in hitResults)
            {
                ARTrackable trackable = singleHit.GetTrackable();
                ARDebug.LogInfo("_DrawARLogo GetTrackable {0}", singleHit.GetTrackable());
                if (trackable is ARPlane && ((ARPlane)trackable).IsPoseInPolygon(singleHit.HitPose) ||
                    trackable is ARPoint)
                {
                    ARAnchor anchor = singleHit.CreateAnchor();

                    Vector3 anchorPosition = anchor.GetPose().position;

                    if (world)
                    {
                        world.transform.position = anchorPosition;
                    }
                    else
                    {
                        world = Instantiate(worldPrefab, anchorPosition, Quaternion.identity);
                    }
                    break;
                }
            }
        }
Exemple #5
0
    public override void OnInspectorGUI()
    {
        ARTrackedObject arto = (ARTrackedObject)target;

        if (arto == null)
        {
            return;
        }

        arto.TrackableTag = EditorGUILayout.TextField("Marker tag", arto.TrackableTag);

        ARTrackable trackable = arto.GetTrackable();

        EditorGUILayout.LabelField("Got marker", trackable == null ? "no" : "yes");
        if (trackable != null)
        {
            string type = ARTrackable.TrackableTypeNames[trackable.Type];
            EditorGUILayout.LabelField("Marker UID", (trackable.UID != ARTrackable.NO_ID ? trackable.UID.ToString() : "Not loaded") + " (" + type + ")");
        }

        EditorGUILayout.Separator();

        arto.secondsToRemainVisible = EditorGUILayout.FloatField("Stay visible", arto.secondsToRemainVisible);

        EditorGUILayout.Separator();

        arto.eventReceiver = (GameObject)EditorGUILayout.ObjectField("Event Receiver:", arto.eventReceiver, typeof(GameObject), true);
    }
Exemple #6
0
 private void _SafeAdd <T>(ARTrackable trackable, List <T> trackables) where T : ARTrackable
 {
     if (trackable is T)
     {
         trackables.Add(trackable as T);
     }
 }
    private static void DrawNFTMarker(ARTrackable m, Matrix4x4 mat, bool selected)
    {
        float pattWidth  = m.NFTWidth;
        float pattHeight = m.NFTHeight;

        //Debug.Log("DrawNFTMarker got pattWidth=" + pattWidth + ", pattHeight=" + pattHeight + ".");
        if (pattWidth > 0.0f && pattHeight > 0.0f)
        {
            float   biggestSide = Math.Max(pattWidth, pattHeight);
            Vector3 origin      = mat.GetColumn(3);
            Vector3 right       = mat.GetColumn(0);
            Vector3 up          = mat.GetColumn(1);
            Vector3 centre      = origin + right * 0.5f * pattWidth + up * 0.5f * pattHeight;

            //float d = selected ? 1.0f : 0.0f;

            DrawRectangle(centre, up, right, pattWidth, pattHeight, selected ? MarkerBorderSelected : MarkerBorderUnselected);
            DrawRectangle(centre, up, right, pattWidth + biggestSide * 0.05f, pattHeight + biggestSide * 0.05f, selected ? MarkerEdgeSelected : MarkerEdgeUnselected);

            //Gizmos.DrawGUITexture(new Rect(centre.x, centre.y, 20, 20), m.MarkerImage);

            float wordUnitSize = pattHeight * 0.02f;
            DrawWord(m.Tag, wordUnitSize, centre - up * (pattHeight * 0.6f + (wordUnitSize * 4)) - right * pattWidth * 0.525f, up, right * 0.5f);
        }
    }
Exemple #8
0
        private void trackTest(Touch touch)
        {
            List <ARHitResult> hitResults = ARFrame.HitTest(touch);

            foreach (ARHitResult singleHit in hitResults)
            {
                ARTrackable trackable = singleHit.GetTrackable();
                if ((trackable is ARPlane && ((ARPlane)trackable).IsPoseInPolygon(singleHit.HitPose)) ||
                    (trackable is ARPoint))
                {
                    ARAnchor anchor = singleHit.CreateAnchor();
                    ARDebug.LogInfo("GridARScript:trackTest anchor world position {0}", anchor.GetPose().position);
                    Vector3 screenPos = Camera.main.WorldToScreenPoint(anchor.GetPose().position);
                    ARDebug.LogInfo("GridARScript:trackTest anchor screen position {0}", screenPos);


                    if (m_touchIndex % 2 == 0)
                    {
                        m_touchBeginModel.GetComponent <disToolLogoVisualizer>().setAnchor(anchor);

                        var script = m_grid.GetComponent <GridARScpript>();
                        if (script)
                        {
                            script.setBeginAnchor(anchor);
                        }
                    }
                    else
                    {
                        m_touchEndModel.GetComponent <disToolLogoVisualizer>().setAnchor(anchor);
                    }
                    ++m_touchIndex;
                    break;
                }
            }
        }
Exemple #9
0
 public bool RemoveTrackable(ARTrackable trackable)
 {
     if (baseTrackable == trackable)
     {
         baseTrackable = null;
     }
     return(trackablesEligibleForBaseTrackable.Remove(trackable));
 }
        //this fuction will not produce more reference
        public ARTrackable AcquireTrackable(IntPtr hitResultHandle)
        {
            IntPtr trackableHandle = IntPtr.Zero;

            NDKAPI.HwArHitResult_acquireTrackable(m_ndkSession.SessionHandle, hitResultHandle, ref trackableHandle);
            ARTrackable trackable = m_ndkSession.TrackableManager.ARTrackableFactory(trackableHandle, true);

            return(trackable);
        }
        private void _DrawARLogo(Touch touch)
        {
            List <ARHitResult> hitResults = ARFrame.HitTest(touch);
            ARHitResult        hitResult  = null;
            ARTrackable        trackable  = null;
            Boolean            hasHitFlag = false;

            ARDebug.LogInfo("_DrawARLogo hitResults count {0}", hitResults.Count);
            foreach (ARHitResult singleHit in hitResults)
            {
                trackable = singleHit.GetTrackable();
                ARDebug.LogInfo("_DrawARLogo GetTrackable {0}", singleHit.GetTrackable());
                if ((trackable is ARPlane && ((ARPlane)trackable).IsPoseInPolygon(singleHit.HitPose)) ||
                    (trackable is ARPoint))
                {
                    hitResult  = singleHit;
                    hasHitFlag = true;
                    if (trackable is ARPlane)
                    {
                        break;
                    }
                }
            }

            if (hasHitFlag != true)
            {
                ARDebug.LogInfo("_DrawARLogo can't hit!");
                return;
            }

            if (addedAnchors.Count > 16)
            {
                ARAnchor toRemove = addedAnchors[0];
                toRemove.Detach();
                addedAnchors.RemoveAt(0);
            }

            GameObject prefab;

            trackable = hitResult.GetTrackable();
            if (trackable is ARPlane)
            {
                prefab = arDiscoveryLogoPlanePrefabs;
            }
            else
            {
                prefab = arDiscoveryLogoPointPrefabs;
            }

/*
 *          ARAnchor anchor = hitResult.CreateAnchor();
 *          var logoObject = Instantiate(prefab, anchor.GetPose().position, anchor.GetPose().rotation);
 *          logoObject.GetComponent<ARDiscoveryLogoVisualizer>().Initialize(anchor);
 *          addedAnchors.Add(anchor);
 */
        }
Exemple #12
0
    // Updates arVisible, arPosition, arRotation based on linked marker state.
    protected virtual void UpdateTracking()
    {
        // Note the current time
        timeLastUpdate = Time.realtimeSinceStartup;

        // First, ensure we have a base marker. If none, then no markers are currently in view.
        ARTrackable trackable = GetTrackable();

        if (trackable == null)
        {
            if (arVisible)
            {
                // Marker was visible but now is hidden.
                timeTrackingLost = timeLastUpdate;
                arVisible        = false;
            }
        }
        else
        {
            if (trackable.Visible)
            {
                Matrix4x4 pose;
                if (Optical && opticalSetupOK)
                {
                    pose = (opticalViewMatrix * trackable.TransformationMatrix).inverse;
                }
                else
                {
                    pose = trackable.TransformationMatrix.inverse;
                }

                arPosition = ARUtilityFunctions.PositionFromMatrix(pose);
                // Camera orientation: In ARToolKit, zero rotation of the camera corresponds to looking vertically down on a marker
                // lying flat on the ground. In Unity however, if we still treat markers as being flat on the ground, we clash with Unity's
                // camera "rotation", because an unrotated Unity camera is looking horizontally.
                // So we choose to treat an unrotated marker as standing vertically, and apply a transform to the scene to
                // to get it to lie flat on the ground.
                arRotation = ARUtilityFunctions.QuaternionFromMatrix(pose);

                if (!arVisible)
                {
                    // Marker was hidden but now is visible.
                    arVisible = true;
                }
            }
            else
            {
                if (arVisible)
                {
                    // Marker was visible but now is hidden.
                    timeTrackingLost = timeLastUpdate;
                    arVisible        = false;
                }
            }
        }
    }
Exemple #13
0
 public void AddTrackable(ARTrackable trackable, bool atHeadOfList = false)
 {
     if (!atHeadOfList)
     {
         trackablesEligibleForBaseTrackable.Add(trackable);
     }
     else
     {
         trackablesEligibleForBaseTrackable.Insert(0, trackable);
     }
 }
Exemple #14
0
 override public void OnMarkerFound(ARTrackable marker)
 {
     if (marker.trackableTag.Equals(marker1Tag))
     {
         marker1 = marker;
     }
     else
     {
         marker2 = marker;
     }
     drawLine(marker);
 }
Exemple #15
0
 override public void OnMarkerLost(ARTrackable marker)
 {
     if (marker.trackableTag.Equals(marker1Tag))
     {
         marker1 = null;
     }
     else
     {
         marker2 = null;
     }
     line.SetWidth(0f, 0f);
 }
Exemple #16
0
        public void GetTrackables <T>(List <T> trackables, ARTrackableQueryFilter filter) where T : ARTrackable
        {
            if (m_lastUpdateFrame < Time.frameCount)
            {
                // Get trackables updated this frame.
                m_ndkSession.FrameAdapter.GetUpdatedTrackables(m_updatedTrackables);

                // Get all the trackables in the session.
                m_ndkSession.SessionAdapter.GetAllTrackables(m_allTrackables);

                ARDebug.LogInfo("m_updatedTrackables {0} m_allTrackables {1}", m_updatedTrackables.Count, m_allTrackables.Count);
                // Find trackables that are not in the hashset (new).
                m_newTrackables.Clear();
                for (int i = 0; i < m_allTrackables.Count; i++)
                {
                    ARTrackable trackable = m_allTrackables[i];
                    if (!m_oldTrackables.Contains(trackable))
                    {
                        m_newTrackables.Add(trackable);
                        m_oldTrackables.Add(trackable);
                    }
                }

                m_lastUpdateFrame = Time.frameCount;
            }

            trackables.Clear();

            if (filter == ARTrackableQueryFilter.ALL)
            {
                for (int i = 0; i < m_allTrackables.Count; i++)
                {
                    _SafeAdd <T>(m_allTrackables[i], trackables);
                }
            }
            else if (filter == ARTrackableQueryFilter.NEW)
            {
                for (int i = 0; i < m_newTrackables.Count; i++)
                {
                    _SafeAdd <T>(m_newTrackables[i], trackables);
                }
            }
            else if (filter == ARTrackableQueryFilter.UPDATED)
            {
                for (int i = 0; i < m_updatedTrackables.Count; i++)
                {
                    _SafeAdd <T>(m_updatedTrackables[i], trackables);
                }
            }
        }
Exemple #17
0
    private void drawLine(ARTrackable marker)
    {
        //Make sure that the tracked marker is one of the markers we are interested in and that we have the other one already loaded
        if (marker1 != null && marker2 != null && (marker.trackableTag.Equals(marker1Tag) || marker.trackableTag.Equals(marker2Tag)))
        {
            Vector3 startPosition = marker1.transform.position;
            line.SetPosition(0, startPosition);

            Vector3 targetPosition = marker2.transform.position;
            line.SetPosition(1, targetPosition);
            line.SetWidth(0.01f, 0.01f);
            float distance = Vector3.Distance(targetPosition, startPosition);
            eventReceiver.BroadcastMessage("OnLineChange", distance, SendMessageOptions.DontRequireReceiver);
            Debug.LogWarning("Distance:" + distance);
        }
    }
 // Return the trackable associated with this component.
 // Uses cached value if available, otherwise performs a find operation.
 public virtual ARTrackable GetTrackable()
 {
     if (_trackable == null)
     {
         // Locate the trackable identified by the tag
         ARTrackable[] ms = FindObjectsOfType <ARTrackable>();
         foreach (ARTrackable m in ms)
         {
             if (m.Tag == _trackableTag)
             {
                 _trackable = m;
                 break;
             }
         }
     }
     return(_trackable);
 }
        private void trackTest()
        {
            if (null == m_beginAnchor)
            {
                m_MeshRenderer.enabled = false;
                return;
            }


            switch (m_beginAnchor.GetTrackingState())
            {
            case ARTrackable.TrackingState.TRACKING:
                m_MeshRenderer.enabled = true;
                break;

            case ARTrackable.TrackingState.PAUSED:
                m_MeshRenderer.enabled = false;
                return;

            case ARTrackable.TrackingState.STOPPED:
            default:
                m_MeshRenderer.enabled = false;
                m_beginAnchor          = null;
                return;
            }

            List <ARHitResult> hitResults = ARFrame.HitTest(m_touchScreenPos.x, m_touchScreenPos.y);

            ARDebug.LogInfo("GridARScript:trackTest hitResults count {0}", hitResults.Count);
            foreach (ARHitResult singleHit in hitResults)
            {
                ARTrackable trackable = singleHit.GetTrackable();
                ARDebug.LogInfo("GridARScript:trackTest GetTrackable {0}", singleHit.GetTrackable());
                if ((trackable is ARPlane && ((ARPlane)trackable).IsPoseInPolygon(singleHit.HitPose)) ||
                    (trackable is ARPoint))
                {
                    ARAnchor anchor = singleHit.CreateAnchor();
                    //ARDebug.LogInfo("GridARScript:trackTest anchor world position {0}", anchor.GetPose().position);

                    renderMesh(m_beginAnchor.GetPose().position, anchor.GetPose().position);
                    break;
                }
            }
        }
    private static void DrawSingleMarker(ARTrackable m, Matrix4x4 mat, bool selected)
    {
        float   pattWidth = m.PatternWidth;
        Vector3 origin    = mat.GetColumn(3);
        Vector3 right     = mat.GetColumn(0);
        Vector3 up        = mat.GetColumn(1);

        //float d = selected ? 1.0f : 0.0f;

        DrawRectangle(origin, up, right, pattWidth * 0.5f, pattWidth * 0.5f, selected ? MarkerBorderSelected : MarkerBorderUnselected); // Inside border.
        DrawRectangle(origin, up, right, pattWidth, pattWidth, selected ? MarkerBorderSelected : MarkerBorderUnselected);               // Edge.
        DrawRectangle(origin, up, right, pattWidth * 1.05f, pattWidth * 1.05f, selected ? MarkerEdgeSelected : MarkerEdgeUnselected);   // Highlighting.

        //Gizmos.DrawGUITexture(new Rect(origin.x, origin.y, 20, 20), m.MarkerImage);

        float wordUnitSize = pattWidth * 0.02f;

        DrawWord(m.Tag, wordUnitSize, origin - up * (pattWidth * 0.6f + (wordUnitSize * 4)) - right * (pattWidth * 0.525f), up, right * 0.5f);
    }
Exemple #21
0
    private static void DrawTwoDMarker(ARTrackable arTrackable, Matrix4x4 mat, bool selected)
    {
        float width  = arTrackable.TwoDImageWidth;
        float height = arTrackable.TwoDImageHeight;

        if (width > 0.0f && height > 0.0f)
        {
            float   biggestSide = Math.Max(width, height);
            Vector3 origin      = mat.GetColumn(3);
            Vector3 right       = mat.GetColumn(0);
            Vector3 up          = mat.GetColumn(1);

            DrawRectangle(origin, up, right, width, height, selected ? MarkerBorderSelected : MarkerBorderUnselected);
            DrawRectangle(origin, up, right, width + biggestSide * 0.05f, height + biggestSide * 0.05f, selected ? MarkerEdgeSelected : MarkerEdgeUnselected);

            float wordUnitSize = height * 0.02f;
            DrawWord(arTrackable.EditorMarkerName, wordUnitSize, origin - up * (height * 0.6f + (wordUnitSize * 4)) - right * width * 0.525f, up, right * 0.5f);
        }
    }
    private static void DrawMarker(ARTrackedCamera tc, bool selected)
    {
        ARTrackable m = tc.GetTrackable();

        if (m == null)
        {
            return;
        }
        if (!m.gameObject.activeInHierarchy)
        {
            return;                                          // Don't attempt to load inactive ARMarkers.
        }
        // Attempt to load. Might not work out if e.g. for a single marker, pattern hasn't been
        // assigned yet, or for an NFT marker, dataset hasn't been specified.
        if (m.UID == ARTrackable.NO_ID)
        {
            m.Load();
        }

        Matrix4x4 pose = tc.gameObject.transform.parent.localToWorldMatrix;

        //ARController.Log("pose=" + pose.ToString("F3"));

        switch (m.Type)
        {
        case ARTrackable.TrackableType.Square:
        case ARTrackable.TrackableType.SquareBarcode:
            DrawSingleMarker(m, pose, selected);
            break;

        case ARTrackable.TrackableType.Multimarker:
            DrawMultiMarker(m, pose, selected);
            break;

        case ARTrackable.TrackableType.NFT:
        case ARTrackable.TrackableType.TwoD:
            DrawNFTMarker(m, pose, selected);
            break;
        }
    }
Exemple #23
0
    private static void DrawMultiMarker(ARTrackable arTrackable, Matrix4x4 mat, bool selected)
    {
        if (null == arTrackable.Patterns)
        {
            return;
        }
        for (int i = 0; i < arTrackable.Patterns.Length; ++i)
        {
            Matrix4x4 mat1      = mat * arTrackable.Patterns[i].matrix;
            float     pattWidth = arTrackable.Patterns[i].width;

            Vector3 origin = mat1.GetColumn(3);
            Vector3 right  = mat1.GetColumn(0);
            Vector3 up     = mat1.GetColumn(1);

            DrawRectangle(origin, up, right, pattWidth * 0.5f, pattWidth * 0.5f, selected ? MarkerBorderSelected : MarkerBorderUnselected); // Inside border.
            DrawRectangle(origin, up, right, pattWidth, pattWidth, selected ? MarkerBorderSelected : MarkerBorderUnselected);               // Edge.
            DrawRectangle(origin, up, right, pattWidth * 1.05f, pattWidth * 1.05f, selected ? MarkerEdgeSelected : MarkerEdgeUnselected);   // Highlighting.

            float wordUnitSize = pattWidth * 0.02f;
            DrawWord(arTrackable.EditorMarkerName + "(" + i + ")", wordUnitSize, origin - up * (pattWidth * 0.6f + (wordUnitSize * 4)) - right * (pattWidth * 0.525f), up, right * 0.5f);
        }
    }
        private void _DrawARLogo(Touch touch)
        {
            List <ARHitResult> hitResults = ARFrame.HitTest(touch);

            foreach (ARHitResult singleHit in hitResults)
            {
                ARTrackable trackable = singleHit.GetTrackable();
                if (trackable is ARPlane && ((ARPlane)trackable).IsPoseInPolygon(singleHit.HitPose))
                {
                    if (addedAnchors.Count > 16)
                    {
                        ARAnchor toRemove = addedAnchors[0];
                        toRemove.Detach();
                        addedAnchors.RemoveAt(0);
                    }
                    ARAnchor anchor     = singleHit.CreateAnchor();
                    var      logoObject = Instantiate(arDiscoveryLogoPrefabs, anchor.GetPose().position, anchor.GetPose().rotation);
                    logoObject.GetComponent <ARDiscoveryLogoVisualizer>().Initialize(anchor);
                    addedAnchors.Add(anchor);
                    break;
                }
            }
        }
Exemple #25
0
        private void _DrawARLogo(Touch touch)
        {
            List <ARHitResult> hitResults = ARFrame.HitTest(touch);

            ARDebug.LogInfo("_DrawARLogo hitResults count {0}", hitResults.Count);
            foreach (ARHitResult singleHit in hitResults)
            {
                ARTrackable trackable = singleHit.GetTrackable();
                ARDebug.LogInfo("_DrawARLogo GetTrackable {0}", singleHit.GetTrackable());
                if ((trackable is ARPlane && ((ARPlane)trackable).IsPoseInPolygon(singleHit.HitPose)) ||
                    (trackable is ARPoint))
                {
                    GameObject prefab;
                    if (trackable is ARPlane)
                    {
                        prefab = arDiscoveryLogoPlanePrefabs;
                    }
                    else
                    {
                        prefab = arDiscoveryLogoPointPrefabs;
                    }

                    if (addedAnchors.Count > 16)
                    {
                        ARAnchor toRemove = addedAnchors[0];
                        toRemove.Detach();
                        addedAnchors.RemoveAt(0);
                    }

                    ARAnchor anchor     = singleHit.CreateAnchor();
                    var      logoObject = Instantiate(prefab, anchor.GetPose().position, anchor.GetPose().rotation);
                    logoObject.GetComponent <ARDiscoveryLogoVisualizer>().Initialize(anchor);
                    addedAnchors.Add(anchor);
                    break;
                }
            }
        }
    public override void OnInspectorGUI()
    {
        EditorGUILayout.BeginVertical();

        // Get the ARTrackable that this panel will edit.
        ARTrackable m = (ARTrackable)target;

        if (m == null)
        {
            return;
        }

        // Attempt to load. Might not work out if e.g. for a single marker, pattern hasn't been
        // assigned yet, or for an NFT marker, dataset hasn't been specified.
        if (m.UID == ARTrackable.NO_ID)
        {
            m.Load();
        }

        // Trackable tag
        m.Tag = EditorGUILayout.TextField("Trackable tag", m.Tag);
        EditorGUILayout.LabelField("UID", (m.UID == ARTrackable.NO_ID ? "Not loaded": m.UID.ToString()));

        EditorGUILayout.Separator();

        // Trackable type
        ARTrackable.TrackableType t = (ARTrackable.TrackableType)EditorGUILayout.EnumPopup("Type", m.Type);
        if (m.Type != t)   // Reload on change.
        {
            m.Unload();
            m.Type = t;
            m.Load();
        }

        // Description of the type of marker
        EditorGUILayout.LabelField("Description", ARTrackable.TrackableTypeNames[m.Type]);

        switch (m.Type)
        {
        case ARTrackable.TrackableType.Square:
        case ARTrackable.TrackableType.SquareBarcode:

            if (m.Type == ARTrackable.TrackableType.Square)
            {
                // For pattern markers, offer a popup with marker pattern file names.
                RefreshPatternFilenames();                         // Update the list of available markers from the resources dir
                if (PatternFilenames.Length > 0)
                {
                    int    patternFilenameIndex = EditorGUILayout.Popup("Pattern file", m.PatternFilenameIndex, PatternFilenames);
                    string patternFilename      = PatternAssets[patternFilenameIndex].name;
                    if (patternFilename != m.PatternFilename)
                    {
                        m.Unload();
                        m.PatternFilenameIndex = patternFilenameIndex;
                        m.PatternFilename      = patternFilename;
                        m.PatternContents      = PatternAssets[m.PatternFilenameIndex].text;
                        m.Load();
                    }
                }
                else
                {
                    m.PatternFilenameIndex = 0;
                    EditorGUILayout.LabelField("Pattern file", "No patterns available");
                    m.PatternFilename = "";
                    m.PatternContents = "";
                }
            }
            else
            {
                // For barcode markers, allow the user to specify the barcode ID.
                long BarcodeID = EditorGUILayout.LongField("Barcode ID", m.BarcodeID);
                if (BarcodeID < 0)
                {
                    BarcodeID = 0;
                }
                ARController arcontroller = Component.FindObjectOfType(typeof(ARController)) as ARController;
                if (arcontroller != null)
                {
                    long maxBarcodeID = barcodeCounts[arcontroller.MatrixCodeType] - 1;
                    if (BarcodeID > maxBarcodeID)
                    {
                        BarcodeID = maxBarcodeID;
                    }
                    EditorGUILayout.LabelField("(in range 0 to " + (barcodeCounts[arcontroller.MatrixCodeType] - 1) + ")");
                }
                if (BarcodeID != m.BarcodeID)
                {
                    m.Unload();
                    m.BarcodeID = BarcodeID;
                    m.Load();
                }
            }

            float patternWidthPrev = m.PatternWidth;
            m.PatternWidth = EditorGUILayout.FloatField("Width", m.PatternWidth);
            if (patternWidthPrev != m.PatternWidth)
            {
                m.Unload();
                m.Load();
            }
            m.UseContPoseEstimation = EditorGUILayout.Toggle("Cont. pose estimation", m.UseContPoseEstimation);

            break;

        case ARTrackable.TrackableType.Multimarker:
            string MultiConfigFile = EditorGUILayout.TextField("Multimarker config.", m.MultiConfigFile);
            if (MultiConfigFile != m.MultiConfigFile)
            {
                m.Unload();
                m.MultiConfigFile = MultiConfigFile;
                m.Load();
            }
            break;

        case ARTrackable.TrackableType.NFT:
            string NFTDataSetName = EditorGUILayout.TextField("NFT dataset name", m.NFTDataName);
            if (NFTDataSetName != m.NFTDataName)
            {
                m.Unload();
                m.NFTDataName = NFTDataSetName;
                m.Load();
            }

            float nftScalePrev = m.NFTScale;
            m.NFTScale = EditorGUILayout.FloatField("NFT marker scalefactor", m.NFTScale);
            if (nftScalePrev != m.NFTScale)
            {
                EditorUtility.SetDirty(m);
            }
            break;

        case ARTrackable.TrackableType.TwoD:
            string TwoDImageFile = EditorGUILayout.TextField("Image file", m.TwoDImageFile);
            if (TwoDImageFile != m.TwoDImageFile)
            {
                m.Unload();
                m.TwoDImageFile = TwoDImageFile;
                m.Load();
            }

            float twoDImageWidthPrev = m.TwoDImageWidth;
            m.TwoDImageWidth = EditorGUILayout.FloatField("Image width", m.TwoDImageWidth);
            if (twoDImageWidthPrev != m.TwoDImageWidth)
            {
                m.Unload();
                m.Load();
            }
            break;
        }

        EditorGUILayout.Separator();

        showFilterOptions = EditorGUILayout.Foldout(showFilterOptions, "Filter Options");
        if (showFilterOptions)
        {
            m.Filtered         = EditorGUILayout.Toggle("Filtered:", m.Filtered);
            m.FilterSampleRate = EditorGUILayout.Slider("Sample rate:", m.FilterSampleRate, 1.0f, 30.0f);
            m.FilterCutoffFreq = EditorGUILayout.Slider("Cutoff freq.:", m.FilterCutoffFreq, 1.0f, 30.0f);
        }

        EditorGUILayout.BeginHorizontal();

        // Draw all the marker images
        if (m.Patterns != null)
        {
            for (int i = 0; i < m.Patterns.Length; i++)
            {
                GUILayout.Label(new GUIContent("Pattern " + i + ", " + m.Patterns[i].width.ToString("n3") + " m", m.Patterns[i].texture), GUILayout.ExpandWidth(false)); // n3 -> 3 decimal places.
            }
        }

        EditorGUILayout.EndHorizontal();
        EditorGUILayout.EndVertical();
    }
//	private Guid   cacheGuid               = Guid.Empty;
//	// When indexes update, there are three likely scenarios:
//	//     1) ID has not changed.
//	//     2) ID has shifted by a few values due to sorting.
//	//     3) Content has been removed, and therefore there is no ID.
//	private int ReassociateContentID(int index, TrackableType markerType, string content) {
//		if (string.CompareOrdinal(ARToolKitAssetManager.AllMarkers[index], content) == 0) {
//			return index;
//		} else {
//			for (int i = 0; i < ARToolKitAssetManager.
//		}
//	}

    public override void OnInspectorGUI()
    {
        // Get the ARMarker that this panel will edit.
        ARTrackable arMarker = (ARTrackable)target;

        if (null == arMarker)
        {
            return;
        }
        // Attempt to load. Might not work out if e.g. for a single marker, pattern hasn't been
        // assigned yet, or for an NFT marker, dataset hasn't been specified.
        if (arMarker.UID == ARTrackable.NO_ID)
        {
            PluginFunctions.arwInitialiseAR();
            arMarker.Load();
        }

        // Check if a new image was dropped into the Project directory
        string        path = Application.streamingAssetsPath + "/" + ARToolKitAssetManager.IMAGES_DIRECTORY_NAME;
        DirectoryInfo dir  = new DirectoryInfo(path);

        FileInfo[] imageFileList = dir.GetFiles("*.jpg").Union(dir.GetFiles("*.jpeg")).ToArray();
        if (imageFileList != null && ARToolKitAssetManager.Images != null && imageFileList.Length != ARToolKitAssetManager.Images.Length)
        {
            if (imageFileList.Length < ARToolKitAssetManager.Images.Length)
            {
                //An image was deleted from the file system so we might have an empty ARTrackable now
                ARController.Log("Warning: Trackable image removed. Please check all ARTrackables and make sure that they have an image assigned.");
            }
            //We found a new trackable in the file system or a trackable was removed lets reload the trackables.
            ARToolKitAssetManager.Reload();
        }

        // Draw the drag n drop area
        DropAreaGUI();

        int selectedMarker = ArrayUtility.IndexOf(ARToolKitAssetManager.AllMarkers, arMarker.EditorMarkerName);

        arMarker.EditorMarkerIndex = EditorGUILayout.Popup("Marker", selectedMarker, ARToolKitAssetManager.AllMarkers);

        bool newSelection = false;

        if (arMarker.EditorMarkerIndex < 0)
        {
            //An image was deleted from the file system so we have an empty ARTrackable now
            ARController.Log("Warning: Trackable image removed. Please check the ARTrackable and make sure that is has an image assigned.");
            return;
        }
        else
        {
            if (string.CompareOrdinal(arMarker.EditorMarkerName, ARToolKitAssetManager.AllMarkers[arMarker.EditorMarkerIndex]) != 0)
            {
                newSelection = true;
                arMarker.EditorMarkerName = ARToolKitAssetManager.AllMarkers[arMarker.EditorMarkerIndex];
            }
        }

        ARTrackable.TrackableType markerType = DetermineTrackableType(arMarker.EditorMarkerIndex);
        if (arMarker.Type != markerType)
        {
            arMarker.ClearUnusedValues();
            arMarker.Type = markerType;
            UpdatePatternDetectionMode();
        }

        EditorGUILayout.LabelField("Type ", ARTrackable.TrackableTypeNames[arMarker.Type]);

        EditorGUILayout.LabelField("Unique ID", (arMarker.UID == ARTrackable.NO_ID ? "Not Loaded": arMarker.UID.ToString()));

        EditorGUILayout.BeginHorizontal();
        // Draw all the marker images
        if (arMarker.Patterns != null)
        {
            for (int i = 0; i < arMarker.Patterns.Length; ++i)
            {
                EditorGUILayout.Separator();
                GUILayout.Label(new GUIContent(string.Format("Pattern {0}, {1}m", i, arMarker.Patterns[i].width.ToString("n3")), arMarker.Patterns[i].texture), GUILayout.ExpandWidth(false));                 // n3 -> 3 decimal places.
            }
        }
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.Separator();

        switch (arMarker.Type)
        {
        case ARTrackable.TrackableType.TwoD:
            if (newSelection)
            {
                arMarker.TwoDImageName = ARToolKitAssetManager.AllMarkers[arMarker.EditorMarkerIndex];
            }
            float twoDImageHeight = EditorGUILayout.FloatField("Image height", arMarker.TwoDImageHeight);
            if (twoDImageHeight != arMarker.TwoDImageHeight)
            {
                EditorUtility.SetDirty(arMarker);
                arMarker.TwoDImageHeight = twoDImageHeight;
            }

            float   width = 0.0f, height = 0.0f;
            int     imageWidth = 0, imageHeight = 0;
            float[] transformation = new float[16];

            if (PluginFunctions.arwGetTrackableAppearanceConfig(arMarker.UID, 0, transformation, out width, out height, out imageWidth, out imageHeight))
            {
                Color32[] imagePixels = new Color32[imageWidth * imageHeight];
                if (PluginFunctions.arwGetTrackableAppearanceImage(arMarker.UID, 0, imagePixels))
                {
                    //Set the texture with the trackable appearance.
                    Texture2D texture = new Texture2D(imageWidth, imageHeight, TextureFormat.RGBA32, true);
                    texture.SetPixels32(imagePixels);
                    texture.Apply();

                    //Display label and texture to the user
                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Label("Trackable Appearance");

                    //Resize texture for viewport with max with and height
                    GUILayout.Label(ARTrackableAppearanceScale.BilinearWithMaxSize(texture, 200, 200));
                    EditorGUILayout.EndHorizontal();
                }
            }
            break;

        case ARTrackable.TrackableType.Square:
            if (newSelection)
            {
                arMarker.PatternContents = GetPatternContents(ARToolKitAssetManager.AllMarkers[arMarker.EditorMarkerIndex]);
            }
            arMarker.PatternWidth          = EditorGUILayout.FloatField("Pattern Width (m)", arMarker.PatternWidth);
            arMarker.UseContPoseEstimation = EditorGUILayout.Toggle("Contstant Pose Estimation", arMarker.UseContPoseEstimation);
            break;

        case ARTrackable.TrackableType.SquareBarcode:
            if (newSelection)
            {
                string[] idArray = ARToolKitAssetManager.AllMarkers[arMarker.EditorMarkerIndex].Split(' ');
                arMarker.BarcodeID = int.Parse(idArray[idArray.Length - 1]);
            }
            arMarker.PatternWidth          = EditorGUILayout.FloatField("Pattern Width (m)", arMarker.PatternWidth);
            arMarker.UseContPoseEstimation = EditorGUILayout.Toggle("Contstant Pose Estimation", arMarker.UseContPoseEstimation);
            break;

        case ARTrackable.TrackableType.Multimarker:
            if (newSelection)
            {
                arMarker.MultiConfigFile = ARToolKitAssetManager.AllMarkers[arMarker.EditorMarkerIndex];
            }
            break;
        }

        EditorGUILayout.Separator();

        arMarker.Filtered = EditorGUILayout.Toggle("Filter Pose", arMarker.Filtered);
        if (arMarker.Filtered)
        {
            arMarker.FilterSampleRate = EditorGUILayout.Slider("Sample Rate", arMarker.FilterSampleRate, 1.0f, 30.0f);
            arMarker.FilterCutoffFreq = EditorGUILayout.Slider("Cutoff Frequency", arMarker.FilterCutoffFreq, 1.0f, 30.0f);
        }

        if (arMarker.Type == ARTrackable.TrackableType.Square || arMarker.Type == ARTrackable.TrackableType.SquareBarcode || arMarker.Type == ARTrackable.TrackableType.Multimarker)
        {
            showGlobalSquareOptions = EditorGUILayout.Foldout(showGlobalSquareOptions, "Global Square Tracking Options");
            if (showGlobalSquareOptions)
            {
                ARController.Instance.TemplateSize = EditorGUILayout.IntSlider("Template Size (bits)", ARController.Instance.TemplateSize, 16, 64);

                int currentTemplateCountMax = ARController.Instance.TemplateCountMax;
                int newTemplateCountMax     = EditorGUILayout.IntField("Maximum Template Count", currentTemplateCountMax);
                if (newTemplateCountMax != currentTemplateCountMax && newTemplateCountMax > 0)
                {
                    ARController.Instance.TemplateCountMax = newTemplateCountMax;
                }

                bool trackInColor = EditorGUILayout.Toggle("Track Templates in Color", ARController.Instance.trackTemplatesInColor);
                if (trackInColor != ARController.Instance.trackTemplatesInColor)
                {
                    ARController.Instance.trackTemplatesInColor = trackInColor;
                    UpdatePatternDetectionMode();
                }

                ARController.Instance.BorderSize    = UnityEngine.Mathf.Clamp(EditorGUILayout.FloatField("Border Size (%)", ARController.Instance.BorderSize), 0.0f, 0.5f);
                ARController.Instance.LabelingMode  = (ARController.ARToolKitLabelingMode)EditorGUILayout.EnumPopup("Marker Border Color", ARController.Instance.LabelingMode);
                ARController.Instance.ImageProcMode = (ARController.ARToolKitImageProcMode)EditorGUILayout.EnumPopup("Image Processing Mode", ARController.Instance.ImageProcMode);
            }
        }

        var obj  = new SerializedObject(arMarker);
        var prop = obj.FindProperty("eventReceivers");

        EditorGUILayout.PropertyField(prop, new GUIContent("Event Receivers"), true);
        obj.ApplyModifiedProperties();
    }
Exemple #28
0
 override public void OnMarkerTracked(ARTrackable marker)
 {
     drawLine(marker);
 }
    // Use LateUpdate to be sure the ARTrackable has updated before we try and use the transformation.
    void LateUpdate()
    {
        // Local scale is always 1 for now
        transform.localScale = Vector3.one;

        // Update tracking if we are running in the Player.
        if (Application.isPlaying)
        {
            // Sanity check, make sure we have an AROrigin in parent hierachy.
            AROrigin origin = GetOrigin();
            if (origin == null)
            {
                //visible = visibleOrRemain = false;
            }
            else
            {
                // Sanity check, make sure we have an ARTrackable assigned.
                ARTrackable trackable = GetTrackable();
                if (trackable == null)
                {
                    //visible = visibleOrRemain = false;
                }
                else
                {
                    // Note the current time
                    float timeNow = Time.realtimeSinceStartup;

                    ARTrackable baseTrackable = origin.GetBaseTrackable();
                    if (baseTrackable != null && trackable.Visible)
                    {
                        if (!visible)
                        {
                            // Trackable was hidden but now is visible.
                            visible = visibleOrRemain = true;
                            if (eventReceiver != null)
                            {
                                eventReceiver.BroadcastMessage("OnTrackableFound", trackable, SendMessageOptions.DontRequireReceiver);
                            }

                            for (int i = 0; i < this.transform.childCount; i++)
                            {
                                this.transform.GetChild(i).gameObject.SetActive(true);
                            }
                        }

                        Matrix4x4 pose;
                        if (trackable == baseTrackable)
                        {
                            // If this marker is the base, no need to take base inverse etc.
                            pose = origin.transform.localToWorldMatrix;
                        }
                        else
                        {
                            pose = (origin.transform.localToWorldMatrix * baseTrackable.TransformationMatrix.inverse * trackable.TransformationMatrix);
                        }
                        transform.position = ARUtilityFunctions.PositionFromMatrix(pose);
                        transform.rotation = ARUtilityFunctions.QuaternionFromMatrix(pose);

                        if (eventReceiver != null)
                        {
                            eventReceiver.BroadcastMessage("OnTrackableTracked", trackable, SendMessageOptions.DontRequireReceiver);
                        }
                    }
                    else
                    {
                        if (visible)
                        {
                            // Trackable was visible but now is hidden.
                            visible          = false;
                            timeTrackingLost = timeNow;
                        }

                        if (visibleOrRemain && (timeNow - timeTrackingLost >= secondsToRemainVisible))
                        {
                            visibleOrRemain = false;
                            if (eventReceiver != null)
                            {
                                eventReceiver.BroadcastMessage("OnTrackableLost", trackable, SendMessageOptions.DontRequireReceiver);
                            }
                            for (int i = 0; i < this.transform.childCount; i++)
                            {
                                this.transform.GetChild(i).gameObject.SetActive(false);
                            }
                        }
                    }
                } // marker
            }     // origin
        }         // Application.isPlaying
    }
Exemple #30
0
 public void RemoveAllTrackables()
 {
     baseTrackable = null;
     trackablesEligibleForBaseTrackable.Clear();
 }