public override  void Bind()
    {
        this.View.mCloseButton.TappedOn             += OnTappedOnCloseButton;
        this.View.mVirtualGreenButton.TappedOn      += OnTappedOnGreenButton;
        this.View.mVirtualYellowButton.TappedOn     += OnTappedOnYellowButton;
        this.View.mVirtualRedButton.TappedOn        += OnTappedOnRedButton;
        this.View.mVirtualBlueButton.TappedOn       += OnTappedOnBlueButton;
        this.View.mAboutButton.TappedOn             += OnTappedOnAboutButton;

        // register Vuforia started callback
        VuforiaAbstractBehaviour vuforiaBehaviour = (VuforiaAbstractBehaviour)FindObjectOfType(typeof(VuforiaAbstractBehaviour));
        if (vuforiaBehaviour)
        {
            vuforiaBehaviour.RegisterVuforiaStartedCallback(EnableContinuousAutoFocus);
            vuforiaBehaviour.RegisterOnPauseCallback(OnPause);
        }
        
         // Find the Wood image target.
        mImageTargetWood = GameObject.Find("ImageTargetWood").GetComponent<ImageTargetBehaviour>();

        // Add a mesh for each virtual button on the Wood target.
        VirtualButtonBehaviour[] vbs =
                mImageTargetWood.gameObject.GetComponentsInChildren<VirtualButtonBehaviour>();
        foreach (VirtualButtonBehaviour vb in vbs)
        {
            CreateVBMesh(vb);
            // Also store the position and scale for later.
            mVBPositionDict.Add(vb.VirtualButtonName, vb.transform.localPosition);
            mVBScaleDict.Add(vb.VirtualButtonName, vb.transform.localScale);
        }
        
    }
 // Add Virtual Buttons that are specified in the configuration data.
 public static void AddVirtualButtons(ImageTargetBehaviour it,
     ConfigData.VirtualButton[] vbs)
 {
     for (int i = 0; i < vbs.Length; ++i)
     {
         AddVirtualButton(it, vbs[i]);
     }
 }
Exemple #3
0
	void Awake () {
		this.imageTargetBehaviour = GetComponent<TrackableBehaviour>() as ImageTargetBehaviour;
		if (this.imageTargetBehaviour != null) {
			this.imageTargetBehaviour.RegisterTrackableEventHandler(this);
		}

		this.IsTracking = false;
		this.ImageTarget = this.gameObject;
		this.SizeInScene = this.imageTargetBehaviour.GetSize();
		this.Artwork = new Artwork(this.title, this.artist, this.artId, this.indexInGraffitiCount, this.artImage, this.drawingReferenceImage, this.orientation, this);
	}
    // Assign material and texture to Image Target.
    public static void UpdateMaterial(ImageTargetBehaviour it)
    {
        // Load reference material.
        string referenceMaterialPath =
            QCARUtilities.GlobalVars.PATH_TO_REFERENCE_MATERIAL;
        Material referenceMaterial =
            (Material)AssetDatabase.LoadAssetAtPath(referenceMaterialPath,
                                                    typeof(Material));
        if (referenceMaterial == null)
        {
            Debug.LogError("Could not find reference material at " +
                           referenceMaterialPath +
                           " please reimport Unity package.");
            return;
        }

        // Load texture from texture folder. Textures have per convention the
        // same name as Image Targets + "_scaled" as postfix.
        string pathToTexture = QCARUtilities.GlobalVars.PATH_TO_TARGET_TEXTURES;
        string textureFile = pathToTexture + it.TrackableName + "_scaled";

        if (File.Exists(textureFile + ".png"))
            textureFile += ".png";
        else if (File.Exists(textureFile + ".jpg"))
            textureFile += ".jpg";

        Texture2D targetTexture =
            (Texture2D)AssetDatabase.LoadAssetAtPath(textureFile,
                                                     typeof(Texture2D));
        if (targetTexture == null)
        {
            // If the texture is null we simply assign a default material.
            it.renderer.sharedMaterial = referenceMaterial;
            return;
        }

        // We create a new material that is based on the reference material but
        // also contains a texture.
        Material materialForTargetTexture = new Material(referenceMaterial);
        materialForTargetTexture.mainTexture = targetTexture;
        materialForTargetTexture.name = targetTexture.name + "Material";
        materialForTargetTexture.mainTextureScale = new Vector2(1, 1);

        it.renderer.sharedMaterial = materialForTargetTexture;

        // Cleanup assets that have been created temporarily.
        EditorUtility.UnloadUnusedAssets();
    }
Exemple #5
0
    private VirtualButtonBehaviour CreateVirtualButton(int id,
                                                       string vbName,
                                                       Vector2 topLeft,
                                                       Vector2 bottomRight,
                                                       ImageTargetBehaviour itb)
    {
        GameObject virtualButtonObject = new GameObject(vbName);
        VirtualButtonBehaviour newVBB =
            virtualButtonObject.AddComponent<VirtualButtonBehaviour>();

        // We need to set the Image Target as a parent BEFORE we set the size
        // of the Virtual Button.
        newVBB.transform.parent = itb.transform;

        Debug.Log("Creating Virtual Button with values: " +
                  "\n ID:           " + id +
                  "\n Name:         " + vbName +
                  "\n Rectangle:    " + topLeft.x + "," +
                                        topLeft.y + "," +
                                        bottomRight.x + "," +
                                        bottomRight.y);

        newVBB.InitializeID(id);
        newVBB.InitializeName(vbName);
        newVBB.SetPosAndScaleFromButtonArea(topLeft, bottomRight);
        // This button is part of a data set and should therefore not be
        // unregistered in native only because the Unity object is destroyed.
        newVBB.UnregisterOnDestroy = false;

        return newVBB;
    }
    // Sets position and scale in the transform component of the Virtual Button
    // game object. The values are calculated from rectangle values (top-left
    // and bottom-right corners).
    // Returns false if Virtual Button is not child of an Image Target.
    public static bool SetPosAndScaleFromButtonArea(Vector2 topLeft,
        Vector2 bottomRight,
        ImageTargetBehaviour it,
        VirtualButtonBehaviour vb)
    {
        if (it == null)
        {
            return false;
        }

        float itScale = it.transform.lossyScale[0];

        Vector2 pos = (topLeft + bottomRight) * 0.5f;

        Vector2 scale = new Vector2(bottomRight[0] - topLeft[0],
                                    topLeft[1] - bottomRight[1]);

        Vector3 vbPosITSpace =
            new Vector3(pos[0] / itScale, VirtualButtonBehaviour.TARGET_OFFSET,
                        pos[1] / itScale);

        Vector3 vbScaleITSpace =
            new Vector3(scale[0],
                        (scale[0] + scale[1]) * 0.5f,
                        scale[1]);

        vb.transform.position = it.transform.TransformPoint(vbPosITSpace);

        // Image Target scale is canceled out (included in both scales)
        vb.transform.localScale =
            vbScaleITSpace / vb.transform.parent.lossyScale[0];

        // Done:
        return true;
    }
Exemple #7
0
 static void updateImageTarget(ImageTargetBehaviour it, DataSetInformation dsInfo, ImageTargetInformation itInfo)
 {
     IEditorImageTargetBehaviour itEditor = it as IEditorImageTargetBehaviour;
     itEditor.SetInitializedInEditor(true);
     itEditor.SetImageTargetType(ImageTargetType.PREDEFINED);
     itEditor.SetDataSetPath("QCAR/" + dsInfo.Name + ".xml");
     itEditor.SetNameForTrackable(itInfo.Name);
     itEditor.SetHeight(itInfo.Height);
     itEditor.SetWidth(itInfo.Width);
 }
Exemple #8
0
    /// <summary>
    /// Enabled/disabled Extended Tracking mode.
    /// </summary>
    /// <param name="ON"></param>
    public virtual void SwitchExtendedTracking(bool extTrackingEnabled)
    {
        StateManager stateManager = TrackerManager.Instance.GetStateManager();

        // We iterate over all TrackableBehaviours to start or stop extended tracking for the targets they represent.
        bool success = true;

        foreach (var tb in stateManager.GetTrackableBehaviours())
        {
            if (tb is ImageTargetBehaviour)
            {
                ImageTargetBehaviour itb = tb as ImageTargetBehaviour;
                if (extTrackingEnabled)
                {
                    if (!itb.ImageTarget.StartExtendedTracking())
                    {
                        success = false;
                        Debug.LogError("Failed to start Extended Tracking on Target " + itb.TrackableName);
                    }
                }
                else
                {
                    itb.ImageTarget.StopExtendedTracking();
                }
            }
            else if (tb is MultiTargetBehaviour)
            {
                MultiTargetBehaviour mtb = tb as MultiTargetBehaviour;
                if (extTrackingEnabled)
                {
                    if (!mtb.MultiTarget.StartExtendedTracking())
                    {
                        success = false;
                        Debug.LogError("Failed to start Extended Tracking on Target " + mtb.TrackableName);
                    }
                }
                else
                {
                    mtb.MultiTarget.StopExtendedTracking();
                }
            }
            else if (tb is CylinderTargetBehaviour)
            {
                CylinderTargetBehaviour ctb = tb as CylinderTargetBehaviour;
                if (extTrackingEnabled)
                {
                    if (!ctb.CylinderTarget.StartExtendedTracking())
                    {
                        success = false;
                        Debug.LogError("Failed to start Extended Tracking on Target " + ctb.TrackableName);
                    }
                }
                else
                {
                    ctb.CylinderTarget.StopExtendedTracking();
                }
            }
            else if (tb is ObjectTargetBehaviour)
            {
                ObjectTargetBehaviour otb = tb as ObjectTargetBehaviour;
                if (extTrackingEnabled)
                {
                    if (!otb.ObjectTarget.StartExtendedTracking())
                    {
                        success = false;
                        Debug.LogError("Failed to start Extended Tracking on Target " + otb.TrackableName);
                    }
                }
                else
                {
                    otb.ObjectTarget.StopExtendedTracking();
                }
            }
            else if (tb is VuMarkBehaviour)
            {
                VuMarkBehaviour vmb = tb as VuMarkBehaviour;
                if (extTrackingEnabled)
                {
                    if (!vmb.VuMarkTemplate.StartExtendedTracking())
                    {
                        success = false;
                        Debug.LogError("Failed to start Extended Tracking on Target " + vmb.TrackableName);
                    }
                }
                else
                {
                    vmb.VuMarkTemplate.StopExtendedTracking();
                }
            }
        }
        mExtTrackingEnabled = success && extTrackingEnabled;
    }
Exemple #9
0
    // Here we handle a cloud target recognition event
    public void  OnNewSearchResult(TargetFinder.TargetSearchResult targetSearchResult)
    {
        int len1 = clone.Length;

        Debug.Log("new Target Found");

        LoadLoadinganimation();  // run AR Loader Animation

        /*****************************************************************************************************
        ** Stop Loading animation
        ***************************************************************************************************** */
/*
 *              //Loading Asset Prefab Set active on new target found
 *              LoadingPrefab.SetActive(true);
 *              //Start Loading animation
 *              foreach (GameObject _loadingassets in loadingAssets)
 *      {
 *                      //ERORRRR set obect to instance first and then use!!!!!!!!!!!
 *                      // get reference Loading Script from the Loading Gameobjects
 *                      LoaderScript loadingScrip = new LoaderScript();
 *                      loadingScrip = _loadingassets.GetComponent<LoaderScript>() as LoaderScript;
 *                      //Set Loading true (Important to read variable exactly from script as Case Sensitive)
 *                      loadingScrip.loading = true;
 *              }
 */
        /*****************************************************************************************************
        ** Stop Loading animation
        ***************************************************************************************************** */


        /*for(i=0; i<num; i++)
         * {
         *              Destroy(clone[i]);
         *      }*/
        //imageTargetBehaviour = new ImageTargetBehaviour();
        newImageTarget       = Instantiate(ImageTargetTemplate.gameObject) as GameObject;
        _imageTargetTemplate = newImageTarget.GetComponent <ImageTargetBehaviour>();
        //TrackerScript = newImageTarget.GetComponent<DefaultTrackableEventHandler>();
        //mTrackableBehaviour = TrackerScript.mTrackableBehaviour;


        //ImageTargetBehaviour imageTargetBehaviour = mImageTracker.TargetFinder.EnableTracking(targetSearchResult, mParentOfImageTargetTemplate);

        // This code demonstrates how to reuse an ImageTargetBehaviour for new search results and modifying it according to the metadata
        // Depending on your application, it can make more sense to duplicate the ImageTargetBehaviour using Instantiate(),
        // or to create a new ImageTargetBehaviour for each new result

        // Vuforia will return a new object with the right script automatically if you use
        // TargetFinder.EnableTracking(TargetSearchResult result, string gameObjectName)



        // enable the new result with the same ImageTargetBehaviour:
        // ImageTargetBehaviour imageTargetBehaviour = mImageTracker.TargetFinder.EnableTracking(targetSearchResult, mParentOfImageTargetTemplate);

        //	if (ImageTargetTemplate) {
        // enable the new result with the same ImageTargetBehaviour:
        ObjectTracker tracker = TrackerManager.Instance.GetTracker <ObjectTracker>();

        imageTargetBehaviour = (ImageTargetBehaviour)tracker.TargetFinder.EnableTracking(targetSearchResult, newImageTarget);                  //mParentOfImageTargetTemplate
        UseExtendedTracking(false);
        //	}

        //Check if the metadata isn't null
        if (targetSearchResult.MetaData == null)
        {
            return;
        }
        // do something with the target metadata
        mTargetMetadata = targetSearchResult.MetaData;
        //mContentManager.TargetCreated(targetSearchResult.MetaData);

        /*if (imageTargetBehaviour != null)
         * {
         * // stop the target finder
         * mCloudRecoBehaviour.CloudRecoEnabled = false;
         * }*/

        /*if (imageTargetBehaviour != null)
         * {
         * // stop the target finder
         * mCloudRecoBehaviour.CloudRecoEnabled = false;
         *
         * // Calls the TargetCreated Method of the SceneManager object to start loading
         * // the BookData from the JSON
         *
         * }*/
        //url = ReadMetaUrl();
        Debug.Log("111111111111");
        //if(String.IsNullOrEmpty(url))
        //{
        url = ReadMetaUrl();
        Debug.Log("Downloading from yes yes worked:" + url);
        Debug.Log("Dodhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh");
        Debug.Log("Read Metadata here");

        //if( _wLoad == true)
        if (_wLoad)
        {
            Debug.Log("Downloading Assets here");
            StartCoroutine("DownloadBundle");
        }

        if (_isScript)
        {
            Debug.Log("Downloading Script now..");
            StartCoroutine("DownloadBundleScript");
        }

        //}

        //Debug.Log("Downloading from yes yes worked:"+ matUrl);

        // use case statements

        else
        {
            Debug.Log("44444444444444");
            if (_IsArt == true)
            {
                Debug.Log("5555555555555555555");
                Debug.Log("ART");
                Debug.Log(_artist);
                Debug.Log(_artistEmail);
                DestroyLoadingAnimation();      // Close AR Loader Animation
            }
        }
    }
Exemple #10
0
 // Start is called before the first frame update
 void Start()
 {
     _redImageTargetBehaviour   = Red.GetComponent <ImageTargetBehaviour>();
     _blueImageTargetBehaviour  = Blue.GetComponent <ImageTargetBehaviour>();
     _greenImageTargetBehaviour = Green.GetComponent <ImageTargetBehaviour>();
 }
Exemple #11
0
 void Start()
 {
     _targetBehaviour = GameObject.Find("ImageTarget").GetComponent <ImageTargetBehaviour>(); //GetComponentInParent<ImageTargetBehaviour>();
     gameObject.layer = 31;
 }
Exemple #12
0
    /// <summary>
    /// Handles new search results
    /// </summary>
    /// <param name="targetSearchResult"></param>
    public void OnNewSearchResult(TargetFinder.TargetSearchResult targetSearchResult)
    {
        // This code demonstrates how to reuse an ImageTargetBehaviour for new search results and modifying it according to the metadata
        // Depending on your application, it can make more sense to duplicate the ImageTargetBehaviour using Instantiate(),
        // or to create a new ImageTargetBehaviour for each new result

        // Vuforia will return a new object with the right script automatically if you use
        // TargetFinder.EnableTracking(TargetSearchResult result, string gameObjectName)

        // Check if the metadata isn't null
        //GameObject newImageTarget =Instantiate(ImageTargetTemplate.gameObject)as GameObject;

        //GameObject augmentation = null;

        //string modelName = targetSearchResult.MetaData;

        if (targetSearchResult.MetaData == null)
        {
            return;
        }

        //if (augmentation != null)
        //	augmentation.transform.parent = newImageTarget.transform;

        // Enable the new result with the same ImageTargetBehaviour:
        ImageTargetBehaviour imageTargetBehaviour = mObjectTracker.TargetFinder.EnableTracking(targetSearchResult, mParentOfImageTargetTemplate) as ImageTargetBehaviour;

        //Debug.Log ("Metadata value is " + modelName);

        switch (targetSearchResult.MetaData)
        {
        case "virus":
            Destroy(GameObject.Find("eubacteria"));
            Destroy(GameObject.Find("lisogenik"));
            break;

        case "eubacteria":
            Destroy(GameObject.Find("virus"));
            Destroy(GameObject.Find("lisogenik"));
            break;

        case "lisogenik":
            Destroy(GameObject.Find("eubacteria"));
            Destroy(GameObject.Find("virus"));
            break;
        }

        if (imageTargetBehaviour != null)
        {
            // Stop the target finder
            mCloudRecoBehaviour.CloudRecoEnabled = false;

            // Stop showing the scan-line
            ShowScanLine(false);

            // Calls the TargetCreated Method of the SceneManager object to start loading
            // the BookData from the JSON
            //mContentManager.TargetCreated(targetSearchResult.MetaData);
            //mContentManager.AnimationsManager.SetInitialAnimationFlags();
        }
    }
 // Start is called before the first frame update
 void Start()
 {
     imageTarget          = GetComponent <ImageTargetBehaviour>();
     imageTargetTransform = imageTarget.transform;
 }
Exemple #14
0
    private void LoadDataSet()
    {
        ObjectTracker tracker = TrackerManager.Instance.GetTracker <ObjectTracker>();

        if (tracker != null)
        {
            Debug.Log("tracker here");
        }
        DataSet dset = tracker.CreateDataSet();

        if (dset.Load(DSPath + "/ds.xml", VuforiaUnity.StorageType.STORAGE_ABSOLUTE))
        {
            Debug.Log("Dataset loaded");
            if (tracker.ActivateDataSet(dset))
            {
                Debug.Log("DS activated");
                requestCheck = true;
                //			deb3.text = "DS activated";
            }
            else
            {
                Debug.Log("DS not activated");
            }
        }
        else
        {
            Debug.LogError("Failed to load dataset!");
            //		deb3.text = "Failed to load dataset!";
        }


        int counter = 0;

        IEnumerable <TrackableBehaviour> tbs = TrackerManager.Instance.GetStateManager().GetTrackableBehaviours();

        foreach (TrackableBehaviour tb in tbs)
        {
            if (tb.name == "New Game Object")
            {
                // change generic name to include trackable name
                tb.gameObject.name = ++counter + ":DynamicImageTarget-" + tb.TrackableName;

                // add additional script components for trackable
                if (tb.TrackableName.Contains("vid_"))
                {
                    VideoTrackableEventHandler vteh = tb.gameObject.AddComponent <VideoTrackableEventHandler>();
                    vteh.mainCanv  = mainCanvas;
                    vteh.riglaCanv = riglaCanvas;
                    GameObject           vGO = Instantiate(videoGO, tb.gameObject.transform);
                    ImageTargetBehaviour itb = (ImageTargetBehaviour)tb;
                    if (tb.TrackableName.Contains("stre"))
                    {
                        if (itb.GetSize().x > itb.GetSize().y)
                        {
                            vGO.transform.localScale = new Vector3(itb.GetSize().x / 100, vGO.transform.localScale.y, itb.GetSize().y / 100);
                        }
                        else
                        {
                            vGO.transform.localScale = new Vector3(itb.GetSize().x / (itb.GetSize().y * 10), vGO.transform.localScale.y, itb.GetSize().y / (itb.GetSize().y * 10));
                        }
                    }
                    else
                    {
                        //  Debug.Log(itb.GetSize());
                        //LOAD videoscale
                        StartCoroutine(DownloadVideoScale(vGO, tb.TrackableName));
                        //END LOAD videoscale
                    }
                    vGO.GetComponentInChildren <VideoPlayer>().url = "http://glazar.pa.infobox.ru/ar/GlazAR/Video/" + tb.TrackableName + ".mp4";
                    VideoController v = vGO.GetComponent <VideoController>();


                    if (tb.TrackableName.Contains("play"))
                    {
                        v.playOnAwake = true;
                    }

                    HandsDeleter hd = tb.gameObject.AddComponent <HandsDeleter>();
                    hd.hands     = handsOn;
                    hd.mainCanv  = mainCanvas;
                    hd.riglaCanv = riglaCanvas;
                    StatGrabber sg = tb.gameObject.AddComponent <StatGrabber>();
                    sg.initstat   = initstat;
                    v.statGrabber = sg;
                    //  v.stat
                }
                else
                {
                    tb.gameObject.AddComponent <ABLoader>();
                    GameObject prl = Instantiate(preloader, tb.gameObject.transform);
                    //       prl.transform.localScale = prl.transform.lossyScale;
                    if (tb.TrackableName.Contains("deadpool"))
                    {
                        deadpoolInteractive a = tb.gameObject.AddComponent <deadpoolInteractive>();
                        a.tagbtns = "deadbuttons";
                    }
                    if (tb.TrackableName.Contains("robottank"))
                    {
                        deadpoolInteractive a = tb.gameObject.AddComponent <deadpoolInteractive>();
                        a.tagbtns = "deadrobotbtns";
                    }
                    if (tb.TrackableName.Contains("tank") || tb.TrackableName.Contains("deadpool"))
                    {
                        ((ImageTarget)tb.Trackable).StartExtendedTracking();
                    }

                    TrackableHandler tr = tb.gameObject.AddComponent <TrackableHandler>();
                    tr.hands     = handsOn;
                    tr.mainCanv  = mainCanvas;
                    tr.riglaCanv = riglaCanvas;
                    if (tb.TrackableName.Contains("pavelg"))
                    {
                        PavelMarker pm = tb.gameObject.AddComponent <PavelMarker>();
                        pm.gatchinaUI = gatchinaPanel;
                    }
                }
                tb.gameObject.AddComponent <TurnOffBehaviour>();
            }
        }
        handsOn.SetActive(true);

        isRunning = false;
    }
Exemple #15
0
 void Start()
 {
     imageTarget = GetComponent <ImageTargetBehaviour>();
 }
    private static void UpdateMesh(ImageTargetBehaviour it)
    {
        GameObject itObject = it.gameObject;

        MeshFilter meshFilter = itObject.GetComponent<MeshFilter>();
        if (!meshFilter)
        {
            meshFilter = itObject.AddComponent<MeshFilter>();
        }

        Vector3 p0, p1, p2, p3;

        if (it.AspectRatio <= 1.0f)
        {
            p0 = new Vector3(-0.5f, 0, -it.AspectRatio * 0.5f);
            p1 = new Vector3(-0.5f, 0, it.AspectRatio * 0.5f);
            p2 = new Vector3(0.5f, 0, -it.AspectRatio * 0.5f);
            p3 = new Vector3(0.5f, 0, it.AspectRatio * 0.5f);
        }
        else
        {
            float aspectRationInv = 1.0f / it.AspectRatio;

            p0 = new Vector3(-aspectRationInv * 0.5f, 0, -0.5f);
            p1 = new Vector3(-aspectRationInv * 0.5f, 0, 0.5f);
            p2 = new Vector3(aspectRationInv * 0.5f, 0, -0.5f);
            p3 = new Vector3(aspectRationInv * 0.5f, 0, 0.5f);
        }

        Mesh mesh = new Mesh();
        mesh.vertices = new Vector3[] { p0, p1, p2, p3 };
        mesh.triangles = new int[]  {
                                        0,1,2,
                                        2,1,3
                                    };

        mesh.normals = new Vector3[mesh.vertices.Length];
        mesh.uv = new Vector2[]{
                new Vector2(0,0),
                new Vector2(0,1),
                new Vector2(1,0),
                new Vector2(1,1)
                };

        mesh.RecalculateNormals();
        meshFilter.mesh = mesh;

        MeshRenderer meshRenderer = itObject.GetComponent<MeshRenderer>();
        if (!meshRenderer)
        {
            meshRenderer = itObject.AddComponent<MeshRenderer>();
        }

        // Cleanup assets that have been created temporarily.
        EditorUtility.UnloadUnusedAssets();
    }
Exemple #17
0
    /// <summary>
    /// Handles new search results
    /// </summary>
    /// <param name="targetSearchResult"></param>
    public void OnNewSearchResult(TargetFinder.TargetSearchResult targetSearchResult)
    {
        // duplicate the referenced image target
        newImageTarget = Instantiate(ImageTargetTemplate.gameObject) as GameObject;

        GameObject augmentation = null;

        TargetFinder.CloudRecoSearchResult cloudRecoSearchResult =
            (TargetFinder.CloudRecoSearchResult)targetSearchResult;

        string model_name = cloudRecoSearchResult.MetaData;


        if (augmentation != null)
        {
            augmentation.transform.parent = newImageTarget.transform;
        }

        // enable the new result with the same ImageTargetBehaviour:
        ObjectTracker        tracker = TrackerManager.Instance.GetTracker <ObjectTracker>();
        ImageTargetBehaviour imageTargetBehaviour =
            (ImageTargetBehaviour)tracker.TargetFinder.EnableTracking(
                targetSearchResult, newImageTarget);


        Debug.Log("Metadata value is " + model_name);
        mTargetMetadata = model_name;
        if (model_name.Contains("video") != true)
        {
            detected = true;
            StartCoroutine(GetAssetBundle());
        }
        else
        {
            Debug.Log("Player Activated");
            GameObject obj;
            obj = (GameObject)Instantiate(video, newImageTarget.transform.position, newImageTarget.transform.rotation);
            //GameObject child =newImageTarget.transform.GetChild(0).gameObject;
            //GameObject child = mTargetMetadata.Find("Video").gameObject;
            //child.SetActive(true);
            obj.transform.parent     = newImageTarget.transform;
            obj.transform.localScale = new Vector3(1, 1, 1);
            obj.transform.rotation   = Quaternion.AngleAxis(90, Vector3.right);
            audioSource = newImageTarget.AddComponent <AudioSource>();
            newImageTarget.GetComponentInChildren <VideoPlayer>().source = VideoSource.Url;

            // Set mode to Audio Source.
            newImageTarget.GetComponentInChildren <VideoPlayer>().audioOutputMode = VideoAudioOutputMode.AudioSource;

            // We want to control one audio track with the video player
            newImageTarget.GetComponentInChildren <VideoPlayer>().controlledAudioTrackCount = 1;

            // We enable the first track, which has the id zero
            newImageTarget.GetComponentInChildren <VideoPlayer>().EnableAudioTrack(0, true);

            // ...and we set the audio source for this track
            newImageTarget.GetComponentInChildren <VideoPlayer>().SetTargetAudioSource(0, audioSource);

            // now set an url to play
            newImageTarget.GetComponentInChildren <VideoPlayer>().url = model_name;
            // player.GetComponent<VideoPlayer>().start = true;
        }

        if (!mIsScanning)
        {
            // stop the target finder
            mCloudRecoBehaviour.CloudRecoEnabled = true;
        }
    }
Exemple #18
0
    // This method creates a single data set from the trackables provided.
    // The method ignores the data set property in TrackableBehaviour and
    // adds all Trackables to a single file.
    // Default Trackables are not added to the data set.
    private ConfigData CreateDataSetFromTrackables(TrackableBehaviour[] trackables)
    {
        // Sanity check.
        if (trackables == null)
        {
            return(null);
        }

        ConfigData sceneData = new ConfigData();

        foreach (TrackableBehaviour tb in trackables)
        {
            // Ignore non-data set trackables.
            if (!(tb is DataSetTrackableBehaviour))
            {
                continue;
            }

            IEditorDataSetTrackableBehaviour trackable = (DataSetTrackableBehaviour)tb;

            string dataSetName   = trackable.DataSetName;
            string trackableName = trackable.TrackableName;

            // We ignore default Trackables or undefined Trackables.
            if (dataSetName == QCARUtilities.GlobalVars.DEFAULT_DATA_SET_NAME ||
                dataSetName == "" ||
                trackableName == QCARUtilities.GlobalVars.DEFAULT_TRACKABLE_NAME ||
                trackableName == "")
            {
                Debug.LogWarning("Ignoring default Trackable for export");
                continue;
            }

            if (trackable.GetType() == typeof(ImageTargetBehaviour))
            {
                ImageTargetBehaviour        it       = (ImageTargetBehaviour)trackable;
                IEditorImageTargetBehaviour editorIt = it;

                ConfigData.ImageTargetData itConfig = new ConfigData.ImageTargetData();

                itConfig.size = editorIt.GetSize();

                // Process Virtual Button list.
                VirtualButtonBehaviour[] vbs =
                    it.GetComponentsInChildren <VirtualButtonBehaviour>();
                itConfig.virtualButtons = new List <ConfigData.VirtualButtonData>(vbs.Length);
                foreach (VirtualButtonBehaviour vb in vbs)
                {
                    Vector2 leftTop;
                    Vector2 rightBottom;
                    if (!vb.CalculateButtonArea(out leftTop,
                                                out rightBottom))
                    {
                        // Invalid Button
                        continue;
                    }

                    ConfigData.VirtualButtonData vbConfig =
                        new ConfigData.VirtualButtonData();

                    IEditorVirtualButtonBehaviour editorVB = vb;
                    vbConfig.name      = editorVB.VirtualButtonName;
                    vbConfig.enabled   = editorVB.enabled;
                    vbConfig.rectangle = new Vector4(leftTop.x,
                                                     leftTop.y,
                                                     rightBottom.x,
                                                     rightBottom.y);
                    vbConfig.sensitivity = editorVB.SensitivitySetting;

                    itConfig.virtualButtons.Add(vbConfig);
                }

                sceneData.SetImageTarget(itConfig, editorIt.TrackableName);
            }
            else if (trackable.GetType() == typeof(MultiTargetBehaviour))
            {
                Debug.Log("Multi Targets not exported.");
            }
            else if (trackable.GetType() == typeof(CylinderTargetBehaviour))
            {
                Debug.Log("Cylinder Targets not exported.");
            }
        }

        return(sceneData);
    }
Exemple #19
0
    private void AddVirtualButtons(VirtualButtonBehaviour[] vbBehaviours)
    {
        for (int i = 0; i < vbBehaviours.Length; ++i)
        {
            VirtualButtonBehaviour virtualButton = vbBehaviours[i];

            if (virtualButton.VirtualButtonName == null)
            {
                Debug.LogError("VirtualButton at " + i +
                               " has no name.");
                continue;
            }

            ImageTargetBehaviour imageTarget = virtualButton.GetImageTarget();

            if (imageTarget == null)
            {
                Debug.LogError("VirtualButton named " +
                               virtualButton.VirtualButtonName +
                               " is not attached to an ImageTarget.");
                continue;
            }

            // Image Target is not part of this data set.
            if (!imageTarget.References(this))
            {
                continue;
            }

            int id = virtualButtonGetId(DataSetPtr, imageTarget.TrackableName,
                                        virtualButton.VirtualButtonName);

            if (id == -1)
            {
                // Create the virtual button
                if (RegisterVirtualButton(virtualButton, imageTarget.TrackableName))
                {
                    Debug.Log("Successfully created virtual button " +
                              virtualButton.VirtualButtonName +
                              " at startup");
                    virtualButton.UnregisterOnDestroy = true;
                    id = virtualButtonGetId(DataSetPtr, imageTarget.TrackableName,
                                            virtualButton.VirtualButtonName);
                }
                else
                {
                    Debug.LogError("Failed to create virtual button " +
                                   virtualButton.VirtualButtonName +
                                   " at startup");
                }
            }

            if (id != -1)
            {
                //  Duplicate check:
                if (!mVBBehaviourDict.ContainsKey(id))
                {
                    // OK:
                    virtualButton.InitializeID(id);
                    mVBBehaviourDict.Add(id, virtualButton);
                    Debug.Log("Found VirtualButton named " +
                              virtualButton.VirtualButtonName + " with id " +
                              virtualButton.ID);

                    // Handle any changes to the virtual button in the scene
                    // that are not reflected in the config file
                    virtualButton.UpdatePose();
                    if (!virtualButton.UpdateAreaRectangle(this) ||
                        !virtualButton.UpdateSensitivity(this))
                    {
                        Debug.LogError("Failed to update virtual button " +
                                       virtualButton.VirtualButtonName +
                                       " at startup");
                    }
                    else
                    {
                        Debug.Log("Updated virtual button " +
                                  virtualButton.VirtualButtonName +
                                  " at startup");
                    }
                }
            }
        }
    }
Exemple #20
0
    // Here we handle a cloud target recognition event
    public void  OnNewSearchResult(TargetFinder.TargetSearchResult targetSearchResult)
    {
        int len1 = clone.Length;

        Debug.Log("new Target Found");

        /*for(i=0; i<num; i++)
         * {
         *              Destroy(clone[i]);
         *      }*/
        //imageTargetBehaviour = new ImageTargetBehaviour();
        newImageTarget = Instantiate(ImageTargetTemplate.gameObject) as GameObject;

        //ImageTargetBehaviour imageTargetBehaviour = mImageTracker.TargetFinder.EnableTracking(targetSearchResult, mParentOfImageTargetTemplate);

        // This code demonstrates how to reuse an ImageTargetBehaviour for new search results and modifying it according to the metadata
        // Depending on your application, it can make more sense to duplicate the ImageTargetBehaviour using Instantiate(),
        // or to create a new ImageTargetBehaviour for each new result

        // Vuforia will return a new object with the right script automatically if you use
        // TargetFinder.EnableTracking(TargetSearchResult result, string gameObjectName)



        // enable the new result with the same ImageTargetBehaviour:
        // ImageTargetBehaviour imageTargetBehaviour = mImageTracker.TargetFinder.EnableTracking(targetSearchResult, mParentOfImageTargetTemplate);

        //	if (ImageTargetTemplate) {
        // enable the new result with the same ImageTargetBehaviour:
        ObjectTracker tracker = TrackerManager.Instance.GetTracker <ObjectTracker>();

        imageTargetBehaviour = (ImageTargetBehaviour)tracker.TargetFinder.EnableTracking(targetSearchResult, newImageTarget);                  //mParentOfImageTargetTemplate
        //	}

        //Check if the metadata isn't null
        if (targetSearchResult.MetaData == null)
        {
            return;
        }
        // do something with the target metadata
        mTargetMetadata = targetSearchResult.MetaData;

        /*if (imageTargetBehaviour != null)
         * {
         * // stop the target finder
         * mCloudRecoBehaviour.CloudRecoEnabled = false;
         * }*/

        /*if (imageTargetBehaviour != null)
         * {
         * // stop the target finder
         * mCloudRecoBehaviour.CloudRecoEnabled = false;
         *
         * // Calls the TargetCreated Method of the SceneManager object to start loading
         * // the BookData from the JSON
         * // mContentManager.TargetCreated(targetSearchResult.MetaData);
         * }*/
        url = ReadMeta();
        Debug.Log("Downloading from yes yes worked:" + url);
        StartCoroutine("DownloadBundle");
    }
 // The one ImageTargetBehaviour instance this accessor belongs to is set in
 // the constructor.
 public ImageTargetAccessor(ImageTargetBehaviour target)
 {
     mTarget = target;
 }
Exemple #22
0
 // The one ImageTargetBehaviour instance this accessor belongs to is set in
 // the constructor.
 public ImageTargetAccessor(ImageTargetBehaviour target)
 {
     mTarget = target;
 }
    void Start()
    {
        // register for the OnInitialized event at the QCARBehaviour
        QCARBehaviour qcarBehaviour = (QCARBehaviour)FindObjectOfType(typeof(QCARBehaviour));
        if (qcarBehaviour)
        {
            qcarBehaviour.RegisterTrackerEventHandler(this);
        }

        // Setup position and size of the camera menu.
        ComputePosition();

        // Find the Wood image target.
        mImageTargetWood = GameObject.Find("ImageTargetWood").GetComponent<ImageTargetBehaviour>();

        // Add a mesh for each virtual button on the Wood target.
        VirtualButtonBehaviour[] vbs =
                mImageTargetWood.gameObject.GetComponentsInChildren<VirtualButtonBehaviour>();
        foreach (VirtualButtonBehaviour vb in vbs)
        {
            CreateVBMesh(vb);
            // Also store the position and scale for later.
            mVBPositionDict.Add(vb.VirtualButtonName, vb.transform.localPosition);
            mVBScaleDict.Add(vb.VirtualButtonName, vb.transform.localScale);
        }
    }
Exemple #24
0
    void LateUpdate()
    {
        switch (mTrackingMode)
        {
        case TrackingMode.DEVICE_ORIENTATION:
        {
            // In this mode, the device orientation is tracked
            // and the object stays at a fixed position in world space

            // Update object rotation so that it always look towards the camera
            // and its "up vector" is always aligned with the gravity direction.
            // NOTE: since we are using DeviceTracker, the World up vector is guaranteed
            // to be aligned (approximately) with the real world gravity direction
            RotateToLookAtCamera();

            if (IsPenguinInView())
            {
                DisplayMessage(msgTapThePenguin);
            }
            else
            {
                DisplayMessage(msgFindThePenguin);
            }
        }
        break;

        case TrackingMode.CONSTRAINED_TO_CAMERA:
        {
            // In this phase, the Penguin is constrained to remain
            // in the camera view, so it follows the user motion
            Vector3 constrainedPos = cam.transform.position + cam.transform.forward * mInitialDistance;
            this.transform.position = constrainedPos;

            // Update object rotation so that it always look towards the camera
            // and its "up vector" is always aligned with the gravity direction.
            // NOTE: since we are using DeviceTracker, the World up vector is guaranteed
            // to be aligned (approximately) with the real world gravity direction
            RotateToLookAtCamera();

            // Check if we were waiting for a UDT creation,
            // and switch mode if UDT was created
            if (mBuildingUDT && udtEventHandler && udtEventHandler.TargetCreated)
            {
                ImageTargetBehaviour trackedTarget = GetActiveTarget();

                if (trackedTarget != null)
                {
                    mBuildingUDT = false;

                    // Switch mode to UDT based tracking
                    mTrackingMode = TrackingMode.UDT_BASED;

                    // Update header text
                    DisplayMessage(msgGetCloser);
                    DisplayModeLabel(msgModeUDT);

                    // Hide quality indicator
                    udtEventHandler.ShowQualityIndicator(false);

                    // Show the penguin
                    ShowPenguin(true);

                    // Wake up the proximity detector
                    if (proximityDetector)
                    {
                        proximityDetector.Sleep(false);
                    }

                    // Save a snapshot of the current position offset
                    // between the object and the target center
                    mPosOffsetAtTargetCreation = this.transform.position - trackedTarget.transform.position;
                }
            }
        }
        break;

        case TrackingMode.UDT_BASED:
        {
            // Update the object world position according to the UDT target position
            ImageTargetBehaviour trackedTarget = GetActiveTarget();
            if (trackedTarget != null)
            {
                this.transform.position = trackedTarget.transform.position + mPosOffsetAtTargetCreation;
            }

            // Update object rotation so that it always look towards the camera
            // and its "up vector" is always aligned with the gravity direction.
            // NOTE: since we are using DeviceTracker, the World up vector is guaranteed
            // to be aligned (approximately) with the real world gravity direction
            RotateToLookAtCamera();
        }
        break;
        }
    }
    // This method checks for duplicate virtual buttons in a given image
    // target and prints an error accordingly.
    private static void DetectDuplicates(ImageTargetBehaviour it)
    {
        VirtualButtonBehaviour[] vbs =
                        it.GetComponentsInChildren<VirtualButtonBehaviour>();

        for (int i = 0; i < vbs.Length; ++i)
        {
            for (int j = i + 1; j < vbs.Length; ++j)
            {
                if (vbs[i].VirtualButtonName == vbs[j].VirtualButtonName)
                {
                    Debug.LogError("Duplicate virtual buttons with name '" +
                        vbs[i].VirtualButtonName + "' detected in " +
                        "Image Target '" + it.TrackableName + "'.");
                }
            }
        }
    }
Exemple #26
0
    // Update is called once per frame
    void Update()
    {
        Vector3 cornerInLocalRef = new Vector3(0.5f, 0, 0.5f);
        // Convert from local ref to world ref
        Vector3 cornerInWorldRef = this.transform.TransformPoint(cornerInLocalRef);
        // Convert from world ref to camera ref
        Vector3 cornerInCameraRef = Camera.main.transform.InverseTransformPoint(cornerInWorldRef);

        //		Debug.Log ("For A = " + cornerInCameraRef.y);
        if (cornerInCameraRef.y > 0)
        {
            flip = false;
        }
        else
        {
            flip = true;
        }
        StateManager sm = TrackerManager.Instance.GetStateManager();
        IEnumerable <TrackableBehaviour> activeTrackables = sm.GetActiveTrackableBehaviours();
        int count = 0;

        foreach (TrackableBehaviour tb in activeTrackables)
        {
            //               TRACKABLE NAME NEEDS TO BE CHANGED
            if (tb.TrackableName == "g")
            {
                count = 1;
            }
        }
        if (count == 1)
        {
            mImageTargetBehaviour = GetComponent <ImageTargetBehaviour>();
            if (mImageTargetBehaviour == null)
            {
                Debug.Log("ImageTargetBehaviour not found ");
                return;
            }
            Vector2 targetSize   = mImageTargetBehaviour.GetSize();
            float   targetAspect = targetSize.x / targetSize.y;

            // We define a point in the target local reference
            // we take the bottom-left corner of the target,
            // just as an example
            // Note: the target reference plane in Unity is X-Z,
            // while Y is the normal direction to the target plane
            Vector3 pointOnTarget = new Vector3(-0.5f, 0, -0.5f / targetAspect);

            // We convert the local point to world coordinates
            Vector3 targetPointInWorldRef = transform.TransformPoint(pointOnTarget);

            // We project the world coordinates to screen coords (pixels)
            Vector3 screenPoint = Camera.main.WorldToScreenPoint(targetPointInWorldRef);

            //           Debug.Log ("FOR LETTER A : " + screenPoint.x + ", " + screenPoint.y + ", " + screenPoint.z);
            x = screenPoint.x;
            y = screenPoint.y;
            z = screenPoint.z;
        }
        else
        {
            x = y = z = 0;
        }
    }
Exemple #27
0
    private void CreateVirtualButtons(ImageTargetBehaviour itb)
    {
        // Allocate array for all Image Targets.
        int numVirtualButtons = imageTargetGetNumVirtualButtons(mDataSetPtr, itb.TrackableName);
        IntPtr virtualButtonDataPtr =
            Marshal.AllocHGlobal(Marshal.SizeOf(typeof(QCARManager.VirtualButtonData)) * numVirtualButtons);
        IntPtr rectangleDataPtr =
            Marshal.AllocHGlobal(Marshal.SizeOf(typeof(VirtualButtonBehaviour.RectangleData)) * numVirtualButtons);

        // Copy Virtual Button data from native.
        imageTargetGetVirtualButtons(virtualButtonDataPtr,
                                     rectangleDataPtr,
                                     numVirtualButtons,
                                     mDataSetPtr,
                                     itb.TrackableName);

        for (int i = 0; i < numVirtualButtons; ++i)
        {
            IntPtr vbPtr = new IntPtr(virtualButtonDataPtr.ToInt32() + i *
                    Marshal.SizeOf(typeof(QCARManager.VirtualButtonData)));
            QCARManager.VirtualButtonData vbData = (QCARManager.VirtualButtonData)
                    Marshal.PtrToStructure(vbPtr, typeof(QCARManager.VirtualButtonData));

            // Do not overwrite existing Virtual Buttons.
            if (mVBBehaviourDict.ContainsKey(vbData.id))
            {
                continue;
            }

            IntPtr rectPtr = new IntPtr(rectangleDataPtr.ToInt32() + i *
                    Marshal.SizeOf(typeof(VirtualButtonBehaviour.RectangleData)));
            VirtualButtonBehaviour.RectangleData rectData = (VirtualButtonBehaviour.RectangleData)
                    Marshal.PtrToStructure(rectPtr, typeof(VirtualButtonBehaviour.RectangleData));

            // QCAR support names up to 64 characters in length, but here we allocate 
            // a slightly larger buffer:
            int nameLength = 128;
            System.Text.StringBuilder vbName = new System.Text.StringBuilder(nameLength);
            if (imageTargetGetVirtualButtonName(mDataSetPtr, itb.TrackableName,
                    i, vbName, nameLength) == 0)
            {
                Debug.LogError("Failed to get virtual button name.");
                continue;
            }
            
            VirtualButtonBehaviour vbb = CreateVirtualButton(
                vbData.id, vbName.ToString(),
                new Vector2(rectData.leftTopX, rectData.leftTopY),
                new Vector2(rectData.rightBottomX, rectData.rightBottomY),
                itb);

            mVBBehaviourDict.Add(vbData.id, vbb);
        }

        Marshal.FreeHGlobal(virtualButtonDataPtr);
        Marshal.FreeHGlobal(rectangleDataPtr);
    }
    /// <summary>
    /// Handles new search results
    /// </summary>
    /// <param name="targetSearchResult"></param>
    public void OnNewSearchResult(TargetFinder.TargetSearchResult targetSearchResult)
    {
        GameObject vcube = GameObject.Find("Cube");

        // This code demonstrates how to reuse an ImageTargetBehaviour for new search results and modifying it according to the metadata
        // Depending on your application, it can make more sense to duplicate the ImageTargetBehaviour using Instantiate(),
        // or to create a new ImageTargetBehaviour for each new result

        // Vuforia will return a new object with the right script automatically if you use
        // TargetFinder.EnableTracking(TargetSearchResult result, string gameObjectName)
        string model_name = targetSearchResult.MetaData;         //check it with

        //Check if the metadata isn't null
        if (targetSearchResult.MetaData == null)
        {
            return;
        }

        Debug.Log("Metadata value is " + model_name);          //check it with


        LoadJSONBookData(model_name);
        if (mBookData != null)
        {
            titleb    = mBookData.BookTitle;
            BundleURL = mBookData.BookDetailUrl;
            Debug.Log("Title" + titleb);

            //mIsBookThumbRequested = true;
        }
        switch (titleb)

        {
        case "assetbundle":
            Debug.Log("call assetbundle loading fuction");
            //assetbundleloadfunction()
            //Handheld.PlayFullScreenMovie ("www.idigisolutions.com/ar/video1.ogg", Color.black, FullScreenMovieControlMode.CancelOnInput);
            //vplayer = GetComponent<importmovie>();
            //var xRenderer = transform.Find("Cube");

            //vcube.SetActive(false);
            //cube.SetActive(false);
            StartCoroutine(DownloadAndCache());
            break;

        case "video":
            Debug.Log("call video streaming function");
            //IVideoBackgroundEventHandler()
            //Handheld.PlayFullScreenMovie ("www.idigisolutions.com/ar/video1.ogg", Color.black, FullScreenMovieControlMode.CancelOnInput);
            //GameObject vcube = GameObject.Find("Cube");
            //vcube.SetActive(true);

            break;
        }
        //string booktitle =
        //Debug.Log(booktitle);


        // we have to check whether to go to assetbundle or to video

        /*if( int = video)
         * {
         *      function(PlayMode video);
         * }
         * else{
         *      StartCoroutine(DownloadAndCache());
         * }*/
        //StartCoroutine(DownloadAndCache());
        // First clear all trackables
        mImageTracker.TargetFinder.ClearTrackables(false);

        // enable the new result with the same ImageTargetBehaviour:
        ImageTargetBehaviour imageTargetBehaviour = mImageTracker.TargetFinder.EnableTracking(targetSearchResult, mParentOfImageTargetTemplate) as ImageTargetBehaviour;

        //if extended tracking was enabled from the menu, we need to start the extendedtracking on the newly found trackble.
        if (CloudRecognitionUIEventHandler.ExtendedTrackingIsEnabled)
        {
            imageTargetBehaviour.ImageTarget.StartExtendedTracking();
        }
    }
    // Update Virtual Buttons from configuration data.
    public static void UpdateVirtualButtons(ImageTargetBehaviour it,
        ConfigData.VirtualButton[] vbs)
    {
        for (int i = 0; i < vbs.Length; ++i)
        {
            // Developer is responsible for deleting Virtual Buttons that
            // are not specified in newly imported config.xml files.
            VirtualButtonBehaviour[] vbBehaviours =
                it.GetComponentsInChildren<VirtualButtonBehaviour>();

            bool vbInScene = false;
            for (int j = 0; j < vbBehaviours.Length; ++j)
            {
                // If the Virtual Button specified in the config.xml file
                // is already part of the scene we fill it with new values.
                if (vbBehaviours[j].VirtualButtonName == vbs[i].name)
                {
                    vbBehaviours[j].enabled = vbs[i].enabled;
                    vbBehaviours[j].SensitivitySetting = vbs[i].sensitivity;
                    VirtualButtonEditor.SetPosAndScaleFromButtonArea(
                        new Vector2(vbs[i].rectangle[0], vbs[i].rectangle[1]),
                        new Vector2(vbs[i].rectangle[2], vbs[i].rectangle[3]),
                        it,
                        vbBehaviours[j]);
                    vbInScene = true;
                }
            }
            if (vbInScene)
            {
                continue;
            }

            // If Virtual Button is not part of the scene we create
            // a new one and add it as a direct child of the ImageTarget.
            ImageTargetEditor.AddVirtualButton(it, vbs[i]);
        }
    }
Exemple #30
0
    public void OnNewTrackableSource(TrackableSource trackableSource)
    {
        targetCounter++;
        objectTracker.DeactivateDataSet(dataSet);
        ImageTargetBehaviour imageTargetCopy = Instantiate(imageTargetTemplate);

        //imageTargetCopy.gameObject.name = "new_Target" + targetCounter;

        dataSet.CreateTrackable(trackableSource, imageTargetCopy.gameObject);

        if (GlobalVariable.MulOrNot == false)
        {
            if (SetSource.isOn == true)
            {                                           //Set Source
                if (GlobalVariable.EmitterOnly == true) // Emitter Only
                {
                    GameObject capsule;
                    if (haveEmitter == 0)
                    {                                                      //the first SOURCE,then create SOURCE
                        imageTargetCopy.gameObject.name = "Emitter_Field"; // Name the Target( Target is also a GameObject!)

                        capsule = GameObject.Instantiate(Axis);
                        //capsule = GameObject.CreatePrimitive (PrimitiveType.Capsule);
                        capsule.name = "eemitter";

                        capsule.transform.parent        = imageTargetCopy.transform;
                        capsule.transform.localScale    = new Vector3(0.015f, 0.015f, 0.015f);
                        capsule.transform.localPosition = new Vector3(0, 0, 0); capsule.transform.Rotate(new Vector3(90, 180, 180));
                        //cylinder.transform.localPosition = imageTargetCopy.transform.position;
                        //print (imageTargetCopy.transform.position.x+","+imageTargetCopy.transform.position.y+","+imageTargetCopy.transform.position.z);
                        capsule.transform.localRotation = Quaternion.identity;
                        //cylinder.transform.parent = imageTargetCopy.gameObject.transform;

                        haveEmitter = 1;
                    }
                    else if (haveEmitter == 1)
                    {                                                      //not the first SOURCE,then renew SOURCE
                        GameObject ob = GameObject.Find("Emitter_Field");
                        ob.name = "Destroyed_Emitter_Field";               // disconnect the old one
                        imageTargetCopy.gameObject.name = "Emitter_Field"; // Name the Target( Target is also a GameObject!)

                        capsule = GameObject.Find("eemitter");

                        capsule.transform.parent        = imageTargetCopy.transform;
                        capsule.transform.localScale    = new Vector3(0.015f, 0.015f, 0.015f);
                        capsule.transform.localPosition = new Vector3(0, 0, 0);
                        capsule.transform.localRotation = Quaternion.identity; capsule.transform.Rotate(new Vector3(90, 180, 180));
                        //cylinder.transform.localPosition = imageTargetCopy.transform.position;
                        //print (imageTargetCopy.transform.position.x+","+imageTargetCopy.transform.position.y+","+imageTargetCopy.transform.position.z);
                    }
                }
                else if (GlobalVariable.EmitterOnly == false)                 // Source
                {
                    GameObject cylinder;
                    if (haveSource == 0)                                  //the first SOURCE,then create SOURCE
                    {
                        imageTargetCopy.gameObject.name = "Source_Field"; // Name the Target( Target is also a GameObject!)

                        cylinder = GameObject.Instantiate(Axis);
                        //cylinder = GameObject.CreatePrimitive (PrimitiveType.Cylinder);
                        cylinder.name = "ssource";

                        cylinder.transform.parent        = imageTargetCopy.transform;
                        cylinder.transform.localScale    = new Vector3(0.015f, 0.015f, 0.015f);
                        cylinder.transform.localPosition = new Vector3(0, 0, 0);
                        //cylinder.transform.localPosition = imageTargetCopy.transform.position;
                        //print (imageTargetCopy.transform.position.x+","+imageTargetCopy.transform.position.y+","+imageTargetCopy.transform.position.z);
                        cylinder.transform.localRotation = Quaternion.identity; cylinder.transform.Rotate(new Vector3(90, 180, 180));
                        //cylinder.transform.parent = imageTargetCopy.gameObject.transform;

                        source_field = StartCoroutine(CreateSourceField());                          //start coroutine
                        haveSource   = 1;
                    }
                    else if (haveSource == 1)                        //not the first SOURCE,then renew SOURCE
                    {
                        GameObject ob = GameObject.Find("Source_Field");
                        ob.name = "Destroyed_Source_Field";                        // disconnect the old one
                        imageTargetCopy.gameObject.name = "Source_Field";          // Name the Target( Target is also a GameObject!)

                        cylinder = GameObject.Find("ssource");

                        cylinder.transform.parent        = imageTargetCopy.transform;
                        cylinder.transform.localScale    = new Vector3(0.015f, 0.015f, 0.015f);
                        cylinder.transform.localPosition = new Vector3(0, 0, 0);
                        cylinder.transform.localRotation = Quaternion.identity; cylinder.transform.Rotate(new Vector3(90, 180, 180));
                        //cylinder.transform.localPosition = imageTargetCopy.transform.position;
                        //print (imageTargetCopy.transform.position.x+","+imageTargetCopy.transform.position.y+","+imageTargetCopy.transform.position.z);

                        StopCoroutine(source_field);                         //end coroutine
                        source_field = StartCoroutine(CreateSourceField());  //start a new coroutine
                    }
                }
            }
            else if (SetSink.isOn == true)
            {
                GameObject sphere;
                if (haveSink == 0)
                {                                                   //the first SINK,then create SINK
                    imageTargetCopy.gameObject.name = "Sink_Field"; // Name the Target( Target is also a GameObject!)

                    sphere = GameObject.Instantiate(Axis);
                    //sphere = GameObject.CreatePrimitive (PrimitiveType.Sphere);
                    sphere.name = "ssink";

                    sphere.transform.parent        = imageTargetCopy.transform;
                    sphere.transform.localScale    = new Vector3(0.015f, 0.015f, 0.015f);
                    sphere.transform.localPosition = new Vector3(0, 0, 0);
                    sphere.transform.localRotation = Quaternion.identity; sphere.transform.Rotate(new Vector3(90, 90, 180));

                    haveSink = 1;
                }
                else if (haveSink == 1)
                {                                                   //not the first SINK,then renew SINK
                    GameObject ob = GameObject.Find("Sink_Field");
                    ob.name = "Destroyed_Sink_Field";               // disconnect the old one
                    imageTargetCopy.gameObject.name = "Sink_Field"; // Name the Target( Target is also a GameObject!)

                    sphere = GameObject.Find("ssink");

                    sphere.transform.parent        = imageTargetCopy.transform;
                    sphere.transform.localScale    = new Vector3(0.015f, 0.015f, 0.015f);
                    sphere.transform.localPosition = new Vector3(0, 0, 0);
                    sphere.transform.localRotation = Quaternion.identity; sphere.transform.Rotate(new Vector3(90, 90, 180));
                }
            }
            else if (SetVortex.isOn == true)
            {
                GameObject cube;
                if (haveVortex == 0)
                {                                                     //the first VORTEX,then create VORTEX
                    imageTargetCopy.gameObject.name = "Vortex_Field"; // Name the Target( Target is also a GameObject!)

                    cube = GameObject.Instantiate(Axis);
                    //cube = GameObject.CreatePrimitive (PrimitiveType.Cube);
                    cube.name = "vvortex";

                    cube.transform.parent     = imageTargetCopy.transform;
                    cube.transform.localScale = new Vector3(0.015f, 0.015f, 0.015f);
                    //cube.transform.localScale = new Vector3(0.00f,0.00f,0.00f);
                    cube.transform.localPosition = new Vector3(0, 0, 0);
                    cube.transform.localRotation = Quaternion.identity; cube.transform.Rotate(new Vector3(90, 90, 180));
                    print("vvortex");

                    haveVortex = 1;
                }
                else if (haveVortex == 1)
                {                                                     //not the first VORTEX,then renew VORTEX
                    GameObject ob = GameObject.Find("Vortex_Field");
                    ob.name = "Destroyed_Vortex_Field";               // disconnect the old one
                    imageTargetCopy.gameObject.name = "Vortex_Field"; // Name the Target( Target is also a GameObject!)

                    cube = GameObject.Find("vvortex");
                    cube.transform.parent     = imageTargetCopy.transform;
                    cube.transform.localScale = new Vector3(0.015f, 0.015f, 0.015f);
                    //cube.transform.localScale = new Vector3(0.00f,0.00f,0.00f);
                    cube.transform.localPosition = new Vector3(0, 0, 0);
                    cube.transform.localRotation = Quaternion.identity; cube.transform.Rotate(new Vector3(90, 90, 180));
                    print("vvortex");
                }
            }
            else if (SetUniform.isOn == true)
            {
                GameObject cylinder;
                if (haveUniform == 0)
                {                                                      //the first UNIFROM,then create UNIFORM
                    imageTargetCopy.gameObject.name = "Uniform_Field"; // Name the Target( Target is also a GameObject!)

                    cylinder = GameObject.Instantiate(Axis);
                    //cylinder = GameObject.CreatePrimitive (PrimitiveType.Cylinder);
                    cylinder.name = "uuniform";

                    cylinder.transform.parent     = imageTargetCopy.transform;
                    cylinder.transform.localScale = new Vector3(0.015f, 0.015f, 0.015f);
                    //cylinder.transform.localScale = new Vector3 (0.00f, 0.00f, 0.00f);
                    cylinder.transform.localPosition = new Vector3(0, 0, 0);
                    cylinder.transform.localRotation = Quaternion.identity; cylinder.transform.Rotate(new Vector3(90, 90, 180));
                    //cylinder.transform.Rotate (0, 0, 90);

                    haveUniform = 1;
                }
                else if (haveUniform == 1)
                {                                                      //not the first UNIFORM,then renew UNIFORM
                    GameObject ob = GameObject.Find("Uniform_Field");
                    ob.name = "Destroyed_Unfirom_Field";               // disconnect the old one
                    imageTargetCopy.gameObject.name = "Uniform_Field"; // Name the Target( Target is also a GameObject!)

                    cylinder = GameObject.Find("uuniform");

                    cylinder.transform.parent     = imageTargetCopy.transform;
                    cylinder.transform.localScale = new Vector3(0.015f, 0.015f, 0.015f);
                    //cylinder.transform.localScale = new Vector3 (0.00f, 0.00f, 0.00f);
                    cylinder.transform.localPosition = new Vector3(0, 0, 0);
                    cylinder.transform.localRotation = Quaternion.identity; cylinder.transform.Rotate(new Vector3(90, 90, 180));
                    //cylinder.transform.Rotate (0, 0, 90);
                }
            }
            else if (SetEmitter.isOn == true)
            {
                GameObject sphere;
                if (haveEmitter == 0)
                {                                                      //the first SINK,then create SINK
                    imageTargetCopy.gameObject.name = "Emitter_Field"; // Name the Target( Target is also a GameObject!)

                    sphere = GameObject.Instantiate(Axis);
                    //sphere = GameObject.CreatePrimitive (PrimitiveType.Sphere);
                    sphere.name = "eemitter";

                    sphere.transform.parent        = imageTargetCopy.transform;
                    sphere.transform.localScale    = new Vector3(0.015f, 0.015f, 0.015f);
                    sphere.transform.localPosition = new Vector3(0, 0, 0);
                    sphere.transform.localRotation = Quaternion.identity; sphere.transform.Rotate(new Vector3(90, 90, 180));

                    haveEmitter = 1;
                }
                else if (haveEmitter == 1)
                {                                                      //not the first SINK,then renew SINK
                    GameObject ob = GameObject.Find("Emitter_Field");
                    ob.name = "Destroyed_Emitter_Field";               // disconnect the old one
                    imageTargetCopy.gameObject.name = "Emitter_Field"; // Name the Target( Target is also a GameObject!)

                    sphere = GameObject.Find("eemitter");

                    sphere.transform.parent        = imageTargetCopy.transform;
                    sphere.transform.localScale    = new Vector3(0.015f, 0.015f, 0.015f);
                    sphere.transform.localPosition = new Vector3(0, 0, 0);
                    sphere.transform.localRotation = Quaternion.identity; sphere.transform.Rotate(new Vector3(90, 90, 180));
                }
            }
        }
        else if (GlobalVariable.MulOrNot == true)
        {
            if (SetSource.isOn == true)
            {            //Set Source
                GameObject cylinder;
                GlobalVariable.num_sources      = GlobalVariable.num_sources + 1;
                imageTargetCopy.gameObject.name = "Source_Field" + GlobalVariable.num_sources;                // Name the Target( Target is also a GameObject!)

                cylinder = GameObject.Instantiate(Axis);
                //cylinder = GameObject.CreatePrimitive (PrimitiveType.Cylinder);
                cylinder.name = "ssource" + GlobalVariable.num_sources;

                cylinder.transform.parent        = imageTargetCopy.transform;
                cylinder.transform.localScale    = new Vector3(0.015f, 0.015f, 0.015f);
                cylinder.transform.localPosition = new Vector3(0, 0, 0);
                cylinder.transform.localRotation = Quaternion.identity; cylinder.transform.Rotate(new Vector3(90, 90, 180));

                source_field = StartCoroutine(CreateSourceField());                  //start coroutine
            }
            else if (SetSink.isOn == true)
            {
                GameObject sphere;
                GlobalVariable.num_sinks        = GlobalVariable.num_sinks + 1;
                imageTargetCopy.gameObject.name = "Sink_Field" + GlobalVariable.num_sinks;                // Name the Target( Target is also a GameObject!)

                sphere = GameObject.Instantiate(Axis);
                //sphere = GameObject.CreatePrimitive (PrimitiveType.Sphere);
                sphere.name = "ssink" + GlobalVariable.num_sinks;

                sphere.transform.parent        = imageTargetCopy.transform;
                sphere.transform.localScale    = new Vector3(0.015f, 0.015f, 0.015f);
                sphere.transform.localPosition = new Vector3(0, 0, 0);
                sphere.transform.localRotation = Quaternion.identity; sphere.transform.Rotate(new Vector3(90, 90, 180));
            }
            else if (SetVortex.isOn == true)
            {
                GameObject cube;
                GlobalVariable.num_vortexes     = GlobalVariable.num_vortexes + 1;
                imageTargetCopy.gameObject.name = "Vortex_Field" + GlobalVariable.num_vortexes;                // Name the Target( Target is also a GameObject!)

                cube = GameObject.Instantiate(Axis);
                //cube = GameObject.CreatePrimitive (PrimitiveType.Cube);
                cube.name = "vvortex" + GlobalVariable.num_vortexes;

                cube.transform.parent        = imageTargetCopy.transform;
                cube.transform.localScale    = new Vector3(0.015f, 0.015f, 0.015f);
                cube.transform.localPosition = new Vector3(0, 0, 0);
                cube.transform.localRotation = Quaternion.identity; cube.transform.Rotate(new Vector3(90, 90, 180));
                //print ("vvortex");
            }
            else if (SetUniform.isOn == true)
            {
                GameObject cylinder;
                GlobalVariable.num_uniforms     = GlobalVariable.num_uniforms + 1;
                imageTargetCopy.gameObject.name = "Uniform_Field" + GlobalVariable.num_uniforms;                // Name the Target( Target is also a GameObject!)

                cylinder = GameObject.Instantiate(Axis);
                //cylinder = GameObject.CreatePrimitive (PrimitiveType.Cylinder);
                cylinder.name = "uuniform" + GlobalVariable.num_uniforms;

                cylinder.transform.parent        = imageTargetCopy.transform;
                cylinder.transform.localScale    = new Vector3(0.015f, 0.015f, 0.015f);
                cylinder.transform.localPosition = new Vector3(0, 0, 0);
                cylinder.transform.localRotation = Quaternion.identity; cylinder.transform.Rotate(new Vector3(90, 90, 180));
                //cylinder.transform.Rotate (0, 0, 90);
            }
            else if (SetEmitter.isOn == true)
            {
                GameObject sphere;
                GlobalVariable.num_emitters     = GlobalVariable.num_emitters + 1;
                imageTargetCopy.gameObject.name = "Emitter_Field" + GlobalVariable.num_emitters;                // Name the Target( Target is also a GameObject!)

                sphere = GameObject.Instantiate(Axis);
                //sphere = GameObject.CreatePrimitive (PrimitiveType.Sphere);
                sphere.name = "eemitter" + GlobalVariable.num_emitters;

                sphere.transform.parent        = imageTargetCopy.transform;
                sphere.transform.localScale    = new Vector3(0.015f, 0.015f, 0.015f);
                sphere.transform.localPosition = new Vector3(0, 0, 0);
                sphere.transform.localRotation = Quaternion.identity; sphere.transform.Rotate(new Vector3(90, 90, 180));
            }
        }

        objectTracker.ActivateDataSet(dataSet);
    }
    private static void AddVirtualButton(ImageTargetBehaviour it,
        ConfigData.VirtualButton vb)
    {
        VirtualButtonBehaviour newVBBehaviour =
            it.CreateVirtualButton(vb.name, new Vector2(0.0f, 0.0f),
                           new Vector2(1.0f, 1.0f));

        VirtualButtonEditor.SetPosAndScaleFromButtonArea(
            new Vector2(vb.rectangle[0], vb.rectangle[1]),
            new Vector2(vb.rectangle[2], vb.rectangle[3]),
            it,
            newVBBehaviour);

        VirtualButtonEditor.CreateVBMesh(newVBBehaviour);

        // Load default material.
        VirtualButtonEditor.CreateMaterial(newVBBehaviour);

        newVBBehaviour.enabled = vb.enabled;

        // Add Component to destroy VirtualButton meshes at runtime.
        newVBBehaviour.gameObject.AddComponent<TurnOffBehaviour>();

        // Make sure Virtual Button is correctly aligned with Image Target
        newVBBehaviour.UpdatePose();
    }
    /// <summary>
    /// UpdatePose() is called each frame to ensure the virtual button is clamped
    /// to the image target plane and remains axis-aligned with respect to the
    /// target. Return true if the defining area of the virtual button has
    /// changed, false otherwise.
    /// </summary>
    public bool UpdatePose()
    {
        // The image target to which the button belongs:
        ImageTargetBehaviour itb = this.GetImageTargetBehaviour();

        // If there is no image target we return:
        if (itb == null)
        {
            return(false);
        }

        // We explicitly disallow any objects with non-uniform scaling in the
        // object hierachy of the virtual button. Combined with a rotation
        // this would result in skewing the virtual button.
        Transform t = transform.parent;

        while (t != null)
        {
            if (t.localScale[0] != t.localScale[1] ||
                t.localScale[0] != t.localScale[2])
            {
                Debug.LogWarning("Detected non-uniform scale in virtual " +
                                 " button object hierarchy. Forcing uniform scaling of " +
                                 "object '" + t.name + "'.");

                //  Force uniform scale:
                t.localScale = new Vector3(t.localScale[0], t.localScale[0],
                                           t.localScale[0]);
            }
            t = t.parent;
        }

        // Remember we have updated once:
        mHasUpdatedPose = true;

        // Clamp to center of parent object:
        if (transform.parent != null &&
            transform.parent.gameObject != itb.gameObject)
        {
            transform.localPosition = Vector3.zero;
        }

        // Clamp position to image target plane:
        Vector3 vbPosITSpace = itb.transform.InverseTransformPoint(
            this.transform.position);

        // Set the y offset in Image Target space:
        vbPosITSpace.y = TARGET_OFFSET;
        Vector3 vbPosWorldSpace = itb.transform.TransformPoint(vbPosITSpace);

        this.transform.position = vbPosWorldSpace;

        // Clamp orientation to the image target plane:
        this.transform.rotation = itb.transform.rotation;

        // Update the button area:
        Vector2 leftTop, rightBottom;

        CalculateButtonArea(out leftTop, out rightBottom);

        // Change the button area only if the change is larger than a fixed
        // proportion of the image target size:
        float threshold = itb.transform.localScale[0] * 0.001f;

        if (!Equals(leftTop, mLeftTop, threshold) ||
            !Equals(rightBottom, mRightBottom, threshold))
        {
            // Area has changed significantly:
            mLeftTop     = leftTop;
            mRightBottom = rightBottom;
            return(true);
        }

        // Area has not changed significantly:
        return(false);
    }
 // Recalculates the aspect ratio of the Image Target from a size vector.
 // Automatically updates mesh as well.
 public static void UpdateAspectRatio(ImageTargetBehaviour it, Vector2 size)
 {
     it.AspectRatio = size[1] / size[0];
     UpdateMesh(it);
 }
Exemple #34
0
    /// <summary>
    /// Takes a new trackable source and adds it to the dataset
    /// This gets called automatically as soon as you 'BuildNewTarget with UserDefinedTargetBuildingBehaviour
    /// </summary>
    public void OnNewTrackableSource(TrackableSource trackableSource)
    {
        m_TargetCounter++;

        // Deactivates the dataset first
        m_ObjectTracker.DeactivateDataSet(m_UDT_DataSet);

        // Destroy the oldest target if the dataset is full or the dataset
        // already contains five user-defined targets.
        int Max = 2;

        //if (controlador.GetTipoARcapturar())
        //{
        //    Max = MAX_TARGETS_GAME_MODE;
        //}
        //else
        //{
        //    Max = MAX_TARGETS;
        //}
        if (!controlador.GetIsMultiTarget())
        {
            Max = MAX_TARGETS_GAME_MODE;
        }
        else
        {
            Max = MAX_TARGETS;
        }

        if (m_UDT_DataSet.HasReachedTrackableLimit() || m_UDT_DataSet.GetTrackables().Count() >= Max)
        {
            IEnumerable <Trackable> trackables = m_UDT_DataSet.GetTrackables();
            Trackable oldest = null;
            foreach (Trackable trackable in trackables)
            {
                if (oldest == null || trackable.ID < oldest.ID)
                {
                    oldest = trackable;
                }
            }

            if (oldest != null)
            {
                Debug.Log("Destroying oldest trackable in UDT dataset: " + oldest.Name);
                m_UDT_DataSet.Destroy(oldest, true);
            }
        }

        // Get predefined trackable and instantiate it
        ImageTargetBehaviour imageTargetCopy = Instantiate(ImageTargetTemplate);

        imageTargetCopy.gameObject.name = "UserDefinedTarget-" + m_TargetCounter;

        // Add the duplicated trackable to the data set and activate it
        m_UDT_DataSet.CreateTrackable(trackableSource, imageTargetCopy.gameObject);

        // Activate the dataset again
        m_ObjectTracker.ActivateDataSet(m_UDT_DataSet);

        // Make sure TargetBuildingBehaviour keeps scanning...
        m_TargetBuildingBehaviour.StartScanning();
    }
    // Updates the scale values in the transform component from a given size.
    public static void UpdateScale(ImageTargetBehaviour it, Vector2 size)
    {
        // Update the scale:

        float childScaleFactor = it.GetSize()[0] / size[0];

        if (it.AspectRatio <= 1.0f)
        {
            it.transform.localScale = new Vector3(size[0], size[0], size[0]);
        }
        else
        {
            it.transform.localScale = new Vector3(size[1], size[1], size[1]);
        }

        // Check if 3D content should keep its size or if it should be scaled
        // with the target.
        if (it.mPreserveChildSize)
        {
            foreach (Transform child in it.transform)
            {
                child.localPosition =
                    new Vector3(child.localPosition.x * childScaleFactor,
                                child.localPosition.y * childScaleFactor,
                                child.localPosition.z * childScaleFactor);

                child.localScale =
                    new Vector3(child.localScale.x * childScaleFactor,
                                child.localScale.y * childScaleFactor,
                                child.localScale.z * childScaleFactor);
            }
        }
    }
Exemple #36
0
 private void StartEasyAr()
 {
     ARBuilder.Instance.InitializeEasyAR(KeyAr);
     ARBuilder.Instance.EasyBuild();
     StartCoroutine(ImageTargetBehaviour.StartToTrack());
 }