Esempio n. 1
0
        public virtual void FireRequest(Action <object, AsyncCompletedEventArgs> callback = null)
        {
            emitted = DateTime.Now;
            try {
                System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
                using (client = new WebClient()) {
                    if (callback != null)
                    {
                        //client.UploadValuesCompleted +=new UploadValuesCompletedEventHandler (callback) ;
                        client.UploadStringCompleted += new UploadStringCompletedEventHandler(callback);
                    }
                    client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

                    NameValueCollection form = new NameValueCollection();
                    form.Add("client_id", _CLIENT_ID);
                    form.Add("client_secret", _CLIENT_SECRET);
                    form.Add("grant_type", "client_credentials");
                    form.Add("scope", "viewables:read%20data:read");

                    string data = "client_id=" + _CLIENT_ID
                                  + "&client_secret=" + _CLIENT_SECRET
                                  + "&grant_type=client_credentials"
                                  + "&scope=viewables:read%20data:read";

                    state = RequestStatus.ePending;
                    //client.UploadValuesAsync (new Uri (ForgeLoaderConstants._forgeoAuth2legged), "POST", form, this) ;
                    client.UploadStringAsync(new Uri(ForgeLoaderConstants._forgeoAuth2legged), "POST", data, this);
                }
            } catch (Exception ex) {
                Debug.Log(ForgeLoader.GetCurrentMethod() + " " + ex.Message);
                state = RequestStatus.eError;
            }
        }
        public virtual IEnumerator _FireRequest_(Action <object, AsyncCompletedEventArgs> callback = null)
        {
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
            using (client = UnityWebRequest.Get(uri.AbsoluteUri)) {
                foreach (DictionaryEntry entry in headers)
                {
                    client.SetRequestHeader(entry.Key.ToString(), entry.Value.ToString());
                }
                state = RequestStatus.ePending;
                //client.DownloadDataAsync (uri, this) ;
                                #if UNITY_2017_2_OR_NEWER
                yield return(client.SendWebRequest());
                                #else
                yield return(client.Send());
                                #endif

                if (client.isNetworkError || client.isHttpError)
                {
                    Debug.Log(ForgeLoader.GetCurrentMethod() + " " + client.error + " - " + client.responseCode);
                    state = RequestStatus.eError;
                }
                else
                {
                    //client.downloadHandler.data
                    //client.downloadHandler.text
                    if (callback != null)
                    {
                        DownloadDataCompletedEventArgs args = new DownloadDataCompletedEventArgs(null, false, this);
                        args.Result = client.downloadHandler.data;
                        callback(this, args);
                    }
                }
            }
        }
Esempio n. 3
0
        //public override void CancelRequest () ;

        public override void ProcessResponse(AsyncCompletedEventArgs e)
        {
            //TimeSpan tm = DateTime.Now - emitted;
            //UnityEngine.Debug.Log ("Received: " + tm.TotalSeconds.ToString () + " / " + uri.ToString ());
            DownloadStringCompletedEventArgs args = e as DownloadStringCompletedEventArgs;
            string result = "";

            if (args == null)
            {
                DownloadDataCompletedEventArgs args2 = e as DownloadDataCompletedEventArgs;
                byte [] bytes = args2.Result;
                //WebHeaderCollection headerCollection = this.client.ResponseHeaders;
                //for ( int i = 0 ; i < headerCollection.Count ; i++ ) {
                //	if ( headerCollection.GetKey (i).ToLower () == "content-encoding" && headerCollection.Get (i).ToLower () == "gzip" ) {
                //		Debug.Log (headerCollection.GetKey (i));
                //	}
                //}
                byte [] b = RequestObjectInterface.Decompress(bytes);
                result = Encoding.UTF8.GetString(b);
            }
            else
            {
                result = args.Result;
            }
            try {
                lmvtkDef = JSON.Parse(result);
                state    = SceneLoadingStatus.eReceived;
            } catch (Exception ex) {
                Debug.Log(ForgeLoader.GetCurrentMethod() + " " + ex.Message);
                state = SceneLoadingStatus.eError;
            } finally {
            }
        }
 public override void FireRequest(Action <object, AsyncCompletedEventArgs> callback = null)
 {
     emitted = DateTime.Now;
     try {
         System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
         using (client = new WebClient()) {
             if (callback != null)
             {
                 client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(callback);
             }
             if (!string.IsNullOrEmpty(bearer))
             {
                 client.Headers.Add("Authorization", "Bearer " + bearer);
             }
             client.Headers.Add("Keep-Alive", "timeout=15, max=100");
             //if ( compression == true )
             //	client.Headers.Add ("Accept-Encoding", "gzip, deflate");
             state = SceneLoadingStatus.ePending;
             client.DownloadStringAsync(uri, this);
         }
     } catch (Exception ex) {
         Debug.Log(ForgeLoader.GetCurrentMethod() + " " + ex.Message);
         state = SceneLoadingStatus.eError;
     }
 }
        public override GameObject BuildScene(string name, bool saveToDisk = false)
        {
            try {
                Dictionary <int, JSONNode> dict = new Dictionary <int, JSONNode> ();
                foreach (KeyValuePair <string, JSONNode> pair in lmvtkDef)
                {
                    dict.Add(pair.Value ["id"].AsInt, pair.Value);
                }
                foreach (Eppy.Tuple <int, GameObject> index in dbIds)
                {
                    JSONNode jsonProps = dict [index.Item1];

                    ForgeProperties propertiesOnObj = index.Item2.AddComponent <ForgeProperties> ();
                    propertiesOnObj.Properties = jsonProps;

                    JSONNode j = FindProperty(jsonProps, "name");
                    if (j != null)
                    {
                        name = GetDefaultValueIfUndefined(j, "value", "");
                        if (!string.IsNullOrEmpty(name))
                        {
                            index.Item2.name = name;
                        }
                    }
                }
            } catch (Exception ex) {
                Debug.Log(ForgeLoader.GetCurrentMethod() + " " + ex.Message);
                state = SceneLoadingStatus.eError;
            }

            base.BuildScene(name, saveToDisk);
            return(gameObject);
        }
        protected IEnumerator UploadAndHandlePhoto(byte[] photo, Matrix4x4 cameraToWorldMatrix)
        {
            if (_photoTaken != null)
            {
                UnityMainThreadDispatcher.Instance().Enqueue(() => {
                    _photoTaken.Play();
                });
            }
            using (UnityWebRequest client = CreateRequest(photo)) {
                                #if UNITY_2017_2_OR_NEWER
                yield return(client.SendWebRequest());
                                #else
                yield return(client.Send());
                                #endif

                if (client.isNetworkError || client.isHttpError)
                {
                    Debug.Log(ForgeLoader.GetCurrentMethod() + " " + client.error + " - " + client.responseCode);
                    ReturnOrLoop(null, Vector3.zero, Quaternion.identity);
                }
                else
                {
                    string jsonString = client.downloadHandler.text;
                    // System.Text.Encoding.UTF8.GetString(client.downloadHandler.data)

                    // Position the camera for raycasting
                    Vector3    position = cameraToWorldMatrix.MultiplyPoint(Vector3.zero);
                    Quaternion rotation = Quaternion.LookRotation(-cameraToWorldMatrix.GetColumn(2), cameraToWorldMatrix.GetColumn(1));
                    ReturnOrLoop(jsonString, position, rotation);
                }
            }
        }
        public override IEnumerator _FireRequest_(Action <object, AsyncCompletedEventArgs> callback = null)
        {
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
            //using ( client =new UnityWebRequest (uri.AbsoluteUri) ) {
            using (client = UnityWebRequest.Get(uri.AbsoluteUri)) {
                //client.SetRequestHeader ("Connection", "keep-alive") ;
                //client.method =UnityWebRequest.kHttpVerbGET ;
                //if ( callback != null )
                //	client.DownloadStringCompleted +=new DownloadStringCompletedEventHandler (callback) ;
                if (!string.IsNullOrEmpty(bearer))
                {
                    client.SetRequestHeader("Authorization", "Bearer " + bearer);
                }
                //client.SetRequestHeader ("Keep-Alive", "timeout=15, max=100");
                if (compression == true)
                {
                    client.SetRequestHeader("Accept-Encoding", "gzip, deflate");
                }
                state = SceneLoadingStatus.ePending;
                //client.DownloadStringAsync (uri, this) ;
#if UNITY_2017_2_OR_NEWER
                yield return(client.SendWebRequest());
#else
                yield return(client.Send());
#endif

                if (client.isNetworkError || client.isHttpError)
                {
                    Debug.Log(ForgeLoader.GetCurrentMethod() + " " + client.error + " - " + client.responseCode);
                    state = SceneLoadingStatus.eError;
                }
                else
                {
                    //client.downloadHandler.data
                    //client.downloadHandler.text
                    if (callback != null)
                    {
                        if (compression == true)
                        {
                            DownloadDataCompletedEventArgs args = new DownloadDataCompletedEventArgs(null, false, this);
                            args.Result = client.downloadHandler.data;
                            callback(this, args);
                        }
                        else
                        {
                            DownloadStringCompletedEventArgs args = new DownloadStringCompletedEventArgs(null, false, this);
                            args.Result = client.downloadHandler.text;
                            callback(this, args);
                        }
                    }
                }
            }
        }
Esempio n. 8
0
        //public override void FireRequest (Action<object, AsyncCompletedEventArgs> callback =null) ;

        //public override void CancelRequest () ;

        public override void ProcessResponse(AsyncCompletedEventArgs e)
        {
            DownloadDataCompletedEventArgs args = e as DownloadDataCompletedEventArgs;

            try {
                image = args.Result;
                state = SceneLoadingStatus.eReceived;
            } catch (Exception ex) {
                Debug.Log(ForgeLoader.GetCurrentMethod() + " " + ex.Message);
                state = SceneLoadingStatus.eError;
            } finally {
            }
        }
        protected void oAuth2Legged()
        {
            oAuth2Legged rest = new oAuth2Legged(CLIENTID, CLIENTSECRET);

            rest.FireRequest(
                (object sender, AsyncCompletedEventArgs args) => {
                if (args == null || args.UserState == null)
                {
                    return;
                }
                if (args.Error != null)
                {
                    UnityMainThreadDispatcher.Instance().Enqueue(() => {
                        Debug.Log(ForgeLoader.GetCurrentMethod() + " " + args.Error.Message);
                    });
                    return;
                }

                //UploadValuesCompletedEventArgs args2 =args as UploadValuesCompletedEventArgs ;
                //byte[] data =args2.Result ;
                //string textData =System.Text.Encoding.UTF8.GetString (data) ;

                UploadValuesCompletedEventArgs args2 = args as UploadValuesCompletedEventArgs;
                string textData = Encoding.UTF8.GetString(args2.Result);

                JSONNode json = JSON.Parse(textData);

                BEARER = json ["access_token"];
                UnityMainThreadDispatcher.Instance().Enqueue(() => {
                    oAuthCompleted.Invoke(BEARER);
                });

                if (LOADERS != null)
                {
                    UnityMainThreadDispatcher.Instance().Enqueue(() => {
                        for (int i = 0; i < LOADERS.Count; i++)
                        {
                            GameObject loader       = LOADERS [i];
                            ForgeLoader forgeLoader = loader.GetComponent <ForgeLoader> ();
                            forgeLoader.BEARER      = BEARER;
                            if (string.IsNullOrEmpty(forgeLoader.URN) || string.IsNullOrEmpty(forgeLoader.SCENEID))
                            {
                                continue;
                            }
                            loader.SetActive(true);
                        }
                    });
                }
            }
                );
        }
        //public override void CancelRequest () ;

        public override void ProcessResponse(AsyncCompletedEventArgs e)
        {
            //TimeSpan tm = DateTime.Now - emitted;
            //UnityEngine.Debug.Log ("Received: " + tm.TotalSeconds.ToString () + " / " + uri.ToString ());
            DownloadStringCompletedEventArgs args = e as DownloadStringCompletedEventArgs;

            try {
                lmvtkDef = JSON.Parse(args.Result);
                state    = SceneLoadingStatus.eReceived;
            } catch (Exception ex) {
                Debug.Log(ForgeLoader.GetCurrentMethod() + " " + ex.Message);
                state = SceneLoadingStatus.eError;
            } finally {
            }
        }
        public void AsyncRequestCompleted(object sender, AsyncCompletedEventArgs args)
        {
            if (args == null || args.UserState == null)
            {
                return;
            }
            IRequestInterface item = args.UserState as IRequestInterface;

            if (args.Error != null)
            {
                Debug.Log(ForgeLoader.GetCurrentMethod() + " " + args.Error.Message);
                item.state = SceneLoadingStatus.eError;
                return;
            }
            //item.state =item.resolved ;
            item.ProcessResponse(args);
        }
Esempio n. 12
0
        public override GameObject BuildScene(string name, bool saveToDisk = false)
        {
            try {
                if (_vertices.Length == 0 || _triangles.Length == 0)
                {
                    state = SceneLoadingStatus.eCancelled;
                    return(gameObject);
                }
                Mesh mesh = new Mesh();
                mesh.vertices  = _vertices;
                mesh.triangles = _triangles;
                if (_uvs != null && _uvs.Length != 0)
                {
                    mesh.uv = _uvs;
                }
                mesh.RecalculateNormals();
                mesh.RecalculateBounds();

                MeshFilter filter = gameObject.AddComponent <MeshFilter> ();
                filter.sharedMesh = mesh;
                MeshRenderer renderer = gameObject.AddComponent <MeshRenderer> ();
                renderer.sharedMaterial = ForgeLoaderEngine.GetDefaultMaterial();
                if (createCollider)
                {
                    MeshCollider collider = gameObject.AddComponent <MeshCollider>();
                    collider.sharedMesh = mesh;
                }
#if UNITY_EDITOR
                if (saveToDisk)
                {
                    AssetDatabase.CreateAsset(mesh, ForgeConstants._resourcesPath + this.loader.PROJECTID + "/" + name + ".asset");
                    //AssetDatabase.SaveAssets () ;
                    //AssetDatabase.Refresh () ;
                    //mesh =AssetDatabase.LoadAssetAtPath<Mesh> (ForgeConstants._resourcesPath + this.loader.PROJECTID + "/" + name + ".asset") ;
                }
#endif

                base.BuildScene(name, saveToDisk);
                state = SceneLoadingStatus.eWaitingMaterial;
            } catch (Exception ex) {
                Debug.Log(ForgeLoader.GetCurrentMethod() + " " + ex.Message);
                state = SceneLoadingStatus.eError;
            }
            return(gameObject);
        }
        public static ForgeLoader AddLoaderToGameObject(GameObject root, string urn, string sceneID, string bearer, bool loadMetadata = true, bool loadMesh = true, bool createColliders = false)
        {
            if (root == null)
            {
                root = new GameObject(ForgeConstants.ROOT);
            }
            root.SetActive(false);
            ForgeLoader loader = root.AddComponent <ForgeLoader> ();

            loader.URN             = urn;
            loader.BEARER          = bearer;
            loader.SCENEID         = sceneID;
            loader.LoadMesh        = loadMesh;
            loader.CreateColliders = createColliders;
            loader.LoadMetadata    = loadMetadata;
            root.SetActive(true);
            return(loader);
        }
        //public override void CancelRequest () ;

        public override void ProcessResponse(AsyncCompletedEventArgs e)
        {
            //TimeSpan tm = DateTime.Now - emitted;
            //UnityEngine.Debug.Log ("Received: " + tm.TotalSeconds.ToString () + " / " + uri.ToString ());
            DownloadDataCompletedEventArgs args = e as DownloadDataCompletedEventArgs;

            try {
                byte [] bytes = args.Result;
                if (compression)
                {
                    bytes = RequestObjectInterface.Decompress(bytes);
                }

                List <Eppy.Tuple <int, int, OpenCTM.Mesh> > tmp = new List <Eppy.Tuple <int, int, OpenCTM.Mesh> > ();
                int len = BitConverter.ToInt32(bytes, 0);
                for (int i = 0; i < len; i++)
                {
                    int dbId   = BitConverter.ToInt32(bytes, ((i * 3) + 1) * sizeof(Int32));
                    int fragId = BitConverter.ToInt32(bytes, ((i * 3) + 2) * sizeof(Int32));
                    int offset = BitConverter.ToInt32(bytes, ((i * 3) + 3) * sizeof(Int32));
                    int end    = bytes.Length;
                    if (i < len - 1)
                    {
                        end = BitConverter.ToInt32(bytes, (((i + 1) * 3) + 3) * sizeof(Int32));
                    }

                    byte [] ctm = RequestObjectInterface.Decompress(bytes.Skip(offset).Take(end - offset).ToArray());

                    System.IO.Stream      readMemory = new System.IO.MemoryStream(ctm);                // (bytes, offset, end - offset);
                    OpenCTM.CtmFileReader reader     = new OpenCTM.CtmFileReader(readMemory);
                    //_openctm.Add (new Eppy.Tuple<int, int, OpenCTM.Mesh> (dbId, fragId, reader.decode ()));
                    Eppy.Tuple <int, int, OpenCTM.Mesh> mesh = _openctm.Single(x => x.Item1 == dbId && x.Item2 == fragId);
                    tmp.Add(new Eppy.Tuple <int, int, OpenCTM.Mesh> (mesh.Item1, mesh.Item2, reader.decode()));
                }
                _openctm.Clear();
                _openctm = tmp;

                state = SceneLoadingStatus.eReceived;
            } catch (Exception ex) {
                Debug.Log(ForgeLoader.GetCurrentMethod() + " " + ex.Message);
                state = SceneLoadingStatus.eError;
            } finally {
            }
        }
Esempio n. 15
0
        //public override void FireRequest () ;

        //public override void CancelRequest () ;

        public override void ProcessResponse(AsyncCompletedEventArgs e)
        {
            //TimeSpan tm = DateTime.Now - emitted;
            //UnityEngine.Debug.Log ("Received: " + tm.TotalSeconds.ToString () + " / " + uri.ToString ());
            DownloadDataCompletedEventArgs args = e as DownloadDataCompletedEventArgs;

            try {
                byte [] bytes = args.Result;
                if (compression)
                {
                    bytes = RequestObjectInterface.Decompress(bytes);
                }

                int      nbCoords = getInt(bytes, 0);
                int      index    = sizeof(Int32);
                float [] coords   = getFloats(bytes, nbCoords, sizeof(int));
                index    += nbCoords * sizeof(float);
                _vertices = new Vector3 [nbCoords / 3];
                for (int i = 0, ii = 0; i < nbCoords; i += 3, ii++)
                {
                    _vertices [ii] = new Vector3(coords [i], coords [i + 1], coords [i + 2]);
                }

                int nbTriangles = getInt(bytes, index);
                index     += sizeof(Int32);
                _triangles = getInts(bytes, nbTriangles, index);
                index     += nbTriangles * sizeof(Int32);

                int nbUVs = getInt(bytes, index);
                index += sizeof(Int32);
                float [] uv_a = nbUVs != 0 ? getFloats(bytes, nbUVs, index) : null;
                _uvs = nbUVs != 0 ? new Vector2 [nbUVs / 2] : null;
                for (int i = 0, ii = 0; i < nbUVs; i += 2, ii++)
                {
                    _uvs [ii] = new Vector2(uv_a [i], uv_a [i + 1]);
                }

                state = SceneLoadingStatus.eReceived;
            } catch (Exception ex) {
                Debug.Log(ForgeLoader.GetCurrentMethod() + " " + ex.Message);
                state = SceneLoadingStatus.eError;
            } finally {
            }
        }
Esempio n. 16
0
        public void ListScenes(string bearer)
        {
            _bearer = bearer;
            ForgeLoader forgeLoader = loader.GetComponent <ForgeLoader> ();
            string      url         = ForgeLoaderConstants._endpoint1 + forgeLoader.URN + "/scenes";
            Hashtable   headers     = new Hashtable();

            headers.Add("Authorization", "Bearer " + _bearer);
            RestClient rest = new RestClient(new System.Uri(url), headers);

            rest.FireRequest(
                (object sender, AsyncCompletedEventArgs args) => {
                if (args == null || args.UserState == null)
                {
                    return;
                }
                if (args.Error != null)
                {
                    UnityMainThreadDispatcher.Instance().Enqueue(() => {
                        Debug.Log(Autodesk.Forge.ForgeToolkit.ForgeLoader.GetCurrentMethod() + " " + args.Error.Message);
                    });
                    return;
                }

                DownloadDataCompletedEventArgs args2 = args as DownloadDataCompletedEventArgs;
                string textData = System.Text.Encoding.UTF8.GetString(args2.Result);

                scenesList = JSON.Parse(textData);

                if (scenesList.AsArray.Count > 0)
                {
                    UnityMainThreadDispatcher.Instance().Enqueue(() => {
                        Dropdown dd = combobox.GetComponent <Dropdown> ();
                        foreach (JSONNode child in scenesList.AsArray)
                        {
                            dd.options.Add(new Dropdown.OptionData(child.Value));
                        }
                        combobox.SetActive(true);
                    });
                }
            }
                );
        }
Esempio n. 17
0
        public virtual IEnumerator _FireRequest_(Action <object, AsyncCompletedEventArgs> callback = null)
        {
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
            WWWForm form = new WWWForm();

            form.AddField("client_id", CLIENT_ID);
            form.AddField("client_secret", CLIENT_SECRET);
            form.AddField("grant_type", "client_credentials");
            form.AddField("scope", "viewables:read data:read");

            using (client = UnityWebRequest.Post(uri.AbsoluteUri, form)) {
                foreach (DictionaryEntry entry in headers)
                {
                    client.SetRequestHeader(entry.Key.ToString(), entry.Value.ToString());
                }
                client.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded");

                state = RequestStatus.ePending;
                //client.DownloadDataAsync (uri, this) ;
                                #if UNITY_2017_2_OR_NEWER
                yield return(client.SendWebRequest());
                                #else
                yield return(client.Send());
                                #endif

                if (client.isNetworkError || client.isHttpError)
                {
                    Debug.Log(ForgeLoader.GetCurrentMethod() + " " + client.error + " - " + client.responseCode);
                    state = RequestStatus.eError;
                }
                else
                {
                    if (callback != null)
                    {
                        UploadValuesCompletedEventArgs args = new UploadValuesCompletedEventArgs(null, false, this);
                        args.Result = client.downloadHandler.data;
                        callback(this, args);
                    }
                }
            }
        }
Esempio n. 18
0
        public void LoadScene(int scene)
        {
            if (scene <= 0 || scene > scenesList.AsArray.Count)
            {
                return;
            }
            scene--;
            ForgeLoader forgeLoader = loader.GetComponent <ForgeLoader> ();

            GameObject obj = new GameObject();

            obj.SetActive(false);
            ForgeLoader objLoader = obj.AddComponent <ForgeLoader> ();

            objLoader.URN                      = forgeLoader.URN;
            objLoader.BEARER                   = _bearer;
            objLoader.SCENEID                  = scenesList.AsArray [scene].Value;
            objLoader.ProcessedNodes           = forgeLoader.ProcessedNodes;
            objLoader.ProcessingNodesCompleted = forgeLoader.ProcessingNodesCompleted;
            obj.SetActive(true);
        }
Esempio n. 19
0
 public virtual void FireRequest(Action <object, AsyncCompletedEventArgs> callback = null)
 {
     emitted = DateTime.Now;
     try {
         System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
         using (client = new WebClient()) {
             if (callback != null)
             {
                 client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(callback);
             }
             foreach (DictionaryEntry entry in headers)
             {
                 client.Headers.Add(entry.Key.ToString(), entry.Value.ToString());
             }
             client.Headers.Add("Keep-Alive", "timeout=15, max=100");
             state = RequestStatus.ePending;
             client.DownloadDataAsync(uri, this);
         }
     } catch (Exception ex) {
         Debug.Log(ForgeLoader.GetCurrentMethod() + " " + ex.Message);
         state = RequestStatus.eError;
     }
 }
        public override void Refresh()
        {
            if (!string.IsNullOrEmpty(_BEARER))
            {
                _CredentialsReceived.Invoke(_BEARER);

                for (int i = 0; _ForgeLoaders != null && i < _ForgeLoaders.Count; i++)
                {
                    GameObject  loader      = _ForgeLoaders [i];
                    ForgeLoader forgeLoader = loader.GetComponent <ForgeLoader> ();
                    if (forgeLoader == null)
                    {
                        continue;
                    }
                    forgeLoader._BEARER = _BEARER;
                    if (string.IsNullOrEmpty(forgeLoader.URN) || string.IsNullOrEmpty(forgeLoader.SCENEID))
                    {
                        continue;
                    }
                    loader.SetActive(true);
                }
            }
        }
Esempio n. 21
0
        public override GameObject BuildScene(string name, bool saveToDisk = false)
        {
            try {
                properties = gameObject.AddComponent <ForgeProperties> ();
                //properties.PropertiesString = lmvtkDef [0].ToString();
                properties.Properties = lmvtkDef [0];

                JSONNode j = FindProperty(lmvtkDef [0], "name");
                if (j != null)
                {
                    name = GetDefaultValueIfUndefined(j, "value", "");
                    if (!string.IsNullOrEmpty(name))
                    {
                        gameObject.name = name;
                    }
                }
            } catch (Exception ex) {
                Debug.Log(ForgeLoader.GetCurrentMethod() + " " + ex.Message);
                state = SceneLoadingStatus.eError;
            }

            base.BuildScene(name, saveToDisk);
            return(gameObject);
        }
 public virtual void FireRequest(Action <object, AsyncCompletedEventArgs> callback = null)
 {
     emitted = DateTime.Now;
     try {
         System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
         using (client = new WebClient()) {
             //client.Headers.Add ("Connection", "keep-alive") ;
             if (callback != null)
             {
                 client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(callback);
             }
             if (!string.IsNullOrEmpty(bearer))
             {
                 client.Headers.Add("Authorization", "Bearer " + bearer);
             }
             if (RequestObjectInterface.IsHoloLens || ForgeLoaderConstants._forceHololens)
             {
                 client.Headers.Add("x-ads-device", "hololens");
             }
             if (RequestObjectInterface.IsDAQRI || ForgeLoaderConstants._forceDAQRI)
             {
                 client.Headers.Add("x-ads-device", "daqri");
             }
             client.Headers.Add("Keep-Alive", "timeout=15, max=100");
             if (compression == true)
             {
                 client.Headers.Add("Accept-Encoding", "gzip, deflate");
             }
             state = SceneLoadingStatus.ePending;
             client.DownloadDataAsync(uri, this);
         }
     } catch (Exception ex) {
         Debug.Log(ForgeLoader.GetCurrentMethod() + " " + ex.Message);
         state = SceneLoadingStatus.eError;
     }
 }
Esempio n. 23
0
        public override void Refresh()
        {
            if (string.IsNullOrEmpty(_CLIENT_ID) || string.IsNullOrEmpty(_CLIENT_SECRET))
            {
                return;
            }

            FireRequest(
                (object sender, AsyncCompletedEventArgs args) => {
                if (args == null || args.UserState == null)
                {
                    return;
                }
                if (args.Error != null)
                {
                    UnityMainThreadDispatcher.Instance().Enqueue(() => {
                        Debug.Log(ForgeLoader.GetCurrentMethod() + " " + args.Error.Message);
                    });
                    return;
                }

                                        #if !UNITY_WSA
                UploadStringCompletedEventArgs args2 = args as UploadStringCompletedEventArgs;
                string textData = args2.Result;
                                        #else
                UploadValuesCompletedEventArgs args2 = args as UploadValuesCompletedEventArgs;
                string textData = System.Text.Encoding.UTF8.GetString(args2.Result);
                                        #endif

                try {
                    credentials = JSON.Parse(textData);
                    expiresAt   = DateTime.Now + TimeSpan.FromSeconds(credentials ["expires_in"].AsDouble - 120 /*2 minutes*/);
                    if (isActive)
                    {
                        _timer = new System.Threading.Timer((obj) => {
                            UnityMainThreadDispatcher.Instance().Enqueue(() => {
                                Refresh();
                            });
                        },
                                                            null,
                                                            Math.Max(2500, (int)(TimeSpan.FromSeconds(credentials ["expires_in"].AsDouble - 120 /*2 minutes*/).TotalMilliseconds)),
                                                            System.Threading.Timeout.Infinite
                                                            );
                    }

                    UnityMainThreadDispatcher.Instance().Enqueue(() => {
                        _CredentialsReceived.Invoke(credentials ["access_token"].Value);

                        for (int i = 0; _ForgeLoaders != null && i < _ForgeLoaders.Count; i++)
                        {
                            GameObject loader       = _ForgeLoaders [i];
                            ForgeLoader forgeLoader = loader.GetComponent <ForgeLoader> ();
                            if (forgeLoader == null)
                            {
                                continue;
                            }
                            forgeLoader._BEARER = credentials ["access_token"].Value;
                            if (string.IsNullOrEmpty(forgeLoader.URN) || string.IsNullOrEmpty(forgeLoader.SCENEID))
                            {
                                continue;
                            }
                            loader.SetActive(true);
                        }
                    });
                } catch (Exception ex) {
                    UnityMainThreadDispatcher.Instance().Enqueue(() => {
                        Debug.Log(ForgeLoader.GetCurrentMethod() + " " + ex.Message);
                    });
                }
            }
                );
        }
        public override GameObject BuildScene(string name, bool saveToDisk = false)
        {
            try {
                foreach (Eppy.Tuple <int, OpenCTM.Mesh> openctm in _openctm)
                {
                    OpenCTM.Mesh ctmMesh = openctm.Item2;
                    if (ctmMesh == null || ctmMesh.getVertexCount() == 0 || ctmMesh.getTriangleCount() == 0)
                    {
                        state = SceneLoadingStatus.eCancelled;
                        return(gameObject);
                    }

                    Eppy.Tuple <int, int, GameObject, JSONNode> item = fragments.Single(x => x.Item1 == openctm.Item1);
                    GameObject meshObject = item.Item3;

                    Mesh       mesh     = new Mesh();
                    Vector3 [] vertices = MeshRequest2.getAsVector3(ctmMesh.vertices);
                    mesh.vertices  = vertices;
                    mesh.triangles = ctmMesh.indices;
                    if (ctmMesh.hasNormals())
                    {
                        mesh.normals = MeshRequest2.getAsVector3(ctmMesh.normals);
                    }
                    for (int i = 0; i < ctmMesh.getUVCount(); i++)
                    {
                        mesh.SetUVs(i, MeshRequest2.getAsVector2List(ctmMesh.texcoordinates [i].values));
                    }

                    mesh.RecalculateNormals();
                    mesh.RecalculateBounds();

                    MeshFilter filter = meshObject.AddComponent <MeshFilter> ();
                    filter.sharedMesh = mesh;
                    MeshRenderer renderer = meshObject.AddComponent <MeshRenderer> ();
                    renderer.sharedMaterial = ForgeLoaderEngine.GetDefaultMaterial();
                    if (createCollider)
                    {
                        MeshCollider collider = meshObject.AddComponent <MeshCollider> ();
                        collider.sharedMesh = mesh;
                    }
#if UNITY_EDITOR
                    if (saveToDisk)
                    {
                        AssetDatabase.CreateAsset(mesh, ForgeConstants._resourcesPath + this.loader.PROJECTID + "/" + GetName(item.Item1) + ".asset");
                        //AssetDatabase.SaveAssets () ;
                        //AssetDatabase.Refresh () ;
                        //mesh =AssetDatabase.LoadAssetAtPath<Mesh> (ForgeConstants._resourcesPath + this.loader.PROJECTID + "/" + name + ".asset") ;
                    }
#endif

                    // Add our material to the queue
                    loader.GetMgr()._materials.Add(item.Item2);
                    //if ( loader.GetMgr ()._materials.Add (item.Item2) ) {
                    //	MaterialRequest req = new MaterialRequest (loader, null, bearer, item.Item2, item.Item4);
                    //	req.gameObject = meshObject;
                    //	if ( fireRequestCallback != null )
                    //		fireRequestCallback (this, req);
                    //}
                }
                base.BuildScene(name, saveToDisk);
                state = SceneLoadingStatus.eWaitingMaterial;
            } catch (Exception ex) {
                Debug.Log(ForgeLoader.GetCurrentMethod() + " " + ex.Message);
                state = SceneLoadingStatus.eError;
            }
            return(gameObject);
        }