Exemplo n.º 1
0
    public static void SubmitBug(string url, string username, string project, string area, string description, string extra, string email, bool forceNewBug = false, int retryCount = 0)
    {
        string bugUrl =
            $"{url}?Description={UnityWebRequest.EscapeURL(description)}&Extra={UnityWebRequest.EscapeURL(extra)}&Email={UnityWebRequest.EscapeURL(email)}&ScoutUserName={UnityWebRequest.EscapeURL(username)}&ScoutProject={UnityWebRequest.EscapeURL(project)}&ScoutArea={UnityWebRequest.EscapeURL(area)}&ForceNewBug={(forceNewBug ? "1" : "0")}";

        var form           = new WWWForm();
        var request        = UnityWebRequest.Post(url, form);
        var asyncOperation = request.SendWebRequest();

        ContinuationManager.Add(() => asyncOperation.isDone, () =>
        {
            bool success = string.IsNullOrEmpty(request.error);
            if (success)
            {
                DebugLog.Log("Bug successfully reported to the 'Unity Version Control' FogBugz database.");
            }
            else
            {
                if (retryCount <= maxRetryCount)
                {
                    SubmitBug(url, username, project, area, description, extra, email, forceNewBug, ++retryCount);
                }
                else
                {
                    DebugLog.LogError("Bug report failed:\n" + request.error);
                }
            }
        });
    }
Exemplo n.º 2
0
    public WWW GET(string url, Dictionary <string, string> headers, IRequestListener requestListener)
    {
        WWW www = new WWW(url, null, headers);

        ContinuationManager.Add(() => www.isDone, () => WaitForRequest(www, requestListener));
        return(www);
    }
    public static void SubmitBug(string url, string username, string project, string area, string description, string extra, string email, bool forceNewBug = false, int retryCount = 0)
    {
        string bugUrl = string.Format("{0}?Description={1}&Extra={2}&Email={3}&ScoutUserName={4}&ScoutProject={5}&ScoutArea={6}&ForceNewBug={7}",
                                      url,
                                      WWW.EscapeURL(description),
                                      WWW.EscapeURL(extra),
                                      WWW.EscapeURL(email),
                                      WWW.EscapeURL(username),
                                      WWW.EscapeURL(project),
                                      WWW.EscapeURL(area),
                                      (forceNewBug ? "1" : "0")
                                      );

        var www = new WWW(bugUrl);

        ContinuationManager.Add(() => www.isDone, () =>
        {
            bool success = string.IsNullOrEmpty(www.error) && www.text.Contains("<Success>");
            if (success)
            {
                DebugLog.Log("Bug successfully reported to the 'Unity Version Control' FogBugz database.");
            }
            else
            {
                if (retryCount <= maxRetryCount)
                {
                    SubmitBug(url, username, project, area, description, extra, email, forceNewBug, ++retryCount);
                }
                else
                {
                    DebugLog.LogError("Bug report failed:\n" + www.error);
                }
            }
        });
    }
Exemplo n.º 4
0
    public static void Get(string url, string type, CsvParseRegime regime, string postfix)
    {
        EditorUtility.DisplayProgressBar("Loading", "Requesting csv file. Please wait...", 0f);
        Debug.Log("Loading csv from: " + url);
        var www = new WWW(url);

        ContinuationManager.Add(() => {
            EditorUtility.DisplayProgressBar("Loading", "Requesting csv file. Please wait...", www.progress);
            return(www.isDone);
        },
                                () => {
            EditorUtility.ClearProgressBar();

            // Let's parse this CSV!
            TextReader sr = new StringReader(www.text);
            try {
                if (regime == CsvParseRegime.ObjectPerRow)
                {
                    ParseCsv2(sr, type, postfix);
                }
                else
                {
                    ParseCsv_Sopog(sr, type, postfix);
                }
            }
            catch (Exception ex) {
                Debug.LogException(ex);
            }
        });
    }
    public static void Init()
    {
        UpdateManager manager = (UpdateManager)EditorWindow.GetWindow(typeof(UpdateManager));

        manager.invoice         = PlayerPrefs.GetString("AIInvoice", string.Empty);
        manager.checkForUpdates = PlayerPrefs.GetInt("checkForUpdates", 1) > 0 ? true : false;
        if (!string.IsNullOrEmpty(manager.invoice))
        {
            manager.loading = true;
            WWWForm form = new WWWForm();
            form.AddField("invoice", manager.invoice);
            var www = new WWW("http://zerano-unity3d.com/checkUpdates.php", form);

            ContinuationManager.Add(() => www.isDone, () =>
            {
                if (!string.IsNullOrEmpty(www.error))
                {
                    Debug.Log("WWW failed: " + www.error);
                }

                if (!www.text.Trim().Equals("false"))
                {
                    string[] all     = www.text.Split(',');
                    manager.examples = new List <string> (all);
                    PlayerPrefs.SetString("AIInvoice", manager.invoice);
                    manager.hasIncoice = true;
                    PlayerPrefs.SetString("AIUpdate", System.DateTime.Today.ToString());
                }
                manager.loading = false;
            });
        }
    }
Exemplo n.º 6
0
    public void ReportBug(string body)
    {
        JSONNode node = new JSONClass();

        Debug.Log("Sending issue...");

        node["body"] = body;
        node["name"] = LocalUserInfo.Me.ClientCharacter.Name;

        byte[] rawdata = Encoding.UTF8.GetBytes(node.ToString());

        Dictionary <string, string> headers = new Dictionary <string, string>();

        headers.Add("Content-Type", "application/json");
        headers.Add("Cookie", CookiesManager.Instance.GetCookiesString());

        WWW req = new WWW(Config.BASE_URL + "/issues/create", rawdata, headers);

        // show the logs only in the editor
        #if UNITY_EDITOR
        ContinuationManager.Add(() => req.isDone, () =>
        {
            if (!string.IsNullOrEmpty(req.error))
            {
                Debug.Log("WWW failed: " + req.error);
            }
            Debug.Log("WWW result : " + req.text);
        });
        #endif
    }
Exemplo n.º 7
0
    static void UpdateFromSpreadsheet()
    {
        UnityDataConnector conn = GameObject.Find("ConnectionExample").GetComponent <UnityDataConnector>();

        string connectionString = conn.webServiceUrl + "?ssid=" + conn.spreadsheetId + "&sheet=" + conn.worksheetName + "&pass="******"&action=GetData";

        Debug.Log("Connecting to webservice on " + connectionString);

        WWW www = new WWW(connectionString);

        ContinuationManager.Add(() => www.isDone, () =>
        {
            if (!string.IsNullOrEmpty(www.error))
            {
                Debug.Log("WWW failed: " + www.error);
            }

            try
            {
                JsonData[] ssObjects = JsonMapper.ToObject <JsonData[]>(www.text);
                Debug.Log("Data Successfully Retrieved!");
                GameObject dataUseExample = Selection.activeObject as GameObject;
                dataUseExample.GetComponent <AdjustBalls>().DoSomethingWithTheData(ssObjects);
            }
            catch
            {
                Debug.LogError("Data error: could not parse retrieved data as json.");
            }
        }
                                );
    }
Exemplo n.º 8
0
    public WWW POST(string url, byte[] data, Dictionary <string, string> headers, IRequestListener requestListener)
    {
        // Force post
        if (data == null)
        {
            data = Encoding.UTF8.GetBytes(" ");
        }
        WWW www = new WWW(url, data, headers);

        ContinuationManager.Add(() => www.isDone, () => WaitForRequest(www, requestListener));

        return(www);
    }
Exemplo n.º 9
0
        public void TestEditorWWW()
        {
#if UNITY_EDITOR
            var www = new WWW("https://tile.mapzen.com/mapzen/vector/v1//buildings,landuse,water,roads/17/70076/48701.json");

            ContinuationManager.Add(() => www.isDone, () => {
                if (!string.IsNullOrEmpty(www.error))
                {
                    Debug.Log("WWW failed: " + www.error);
                }
                Debug.Log("[GOMap Editor] Request success: " + www.text);
            });
#endif
        }
Exemplo n.º 10
0
    public static void ShowWindow(string startProduct)
    {
        RDExtensionWindow window;

        window = GetWindow <RDExtensionWindow>();
        Texture2D icon = (Texture2D)EditorGUIUtility.Load("Rogo Digital/Shared/RogoDigital_Icon.png");

        window.titleContent = new GUIContent("Extensions", icon);

        ContinuationManager.Add(() => window.gotListing, () => {
            if (window.headerLinks.Contains(startProduct))
            {
                window.currentFilter = window.headerLinks.IndexOf(startProduct);
            }
        });
    }
    private void DownloadItem(ItemListing listing, bool silentInstall = false)
    {
        downloading = true;
#if UNITY_2018_3_OR_NEWER
        downloadConnection = UnityWebRequest.Get(baseAddress + listing.url);
        downloadConnection.SendWebRequest();
#else
        downloadConnection = new WWW(baseAddress + listing.url);
#endif
        currentExtension = listing.name;

        ContinuationManager.Add(() => downloadConnection.isDone, () =>
        {
            if (downloading)
            {
                downloading = false;
                if (!string.IsNullOrEmpty(downloadConnection.error))
                {
                    Debug.LogError(downloadConnection.error);
                    ShowNotification(new GUIContent(currentExtension + " - Download Failed"));
                }
                else if (downloadConnection.isDone)
                {
#if UNITY_2018_3_OR_NEWER
                    File.WriteAllBytes(Application.dataPath + "/" + currentExtension + ".unitypackage", downloadConnection.downloadHandler.data);
#else
                    File.WriteAllBytes(Application.dataPath + "/" + currentExtension + ".unitypackage", downloadConnection.bytes);
#endif
                    if (!silentInstall)
                    {
                        ShowNotification(new GUIContent(currentExtension + " Downloaded"));
                    }
                    AssetDatabase.ImportPackage(Application.dataPath + "/" + currentExtension + ".unitypackage", !silentInstall);
                    File.Delete(Application.dataPath + "/" + currentExtension + ".unitypackage");
                    if (silentInstall)
                    {
                        Close();
                    }
                }
                else
                {
                    ShowNotification(new GUIContent(currentExtension + " Download Cancelled"));
                }
            }
        });
    }
Exemplo n.º 12
0
        public IEnumerator TestEditorUnityWebRequest()
        {
#if UNITY_EDITOR
            var www = UnityWebRequest.Get("https://tile.nextzen.org/tilezen/vector/v1/all/17/70076/48701.json");
            yield return(www.SendWebRequest());

            ContinuationManager.Add(() => www.isDone, () =>
            {
                if (!string.IsNullOrEmpty(www.error))
                {
                    Debug.Log("UnityWebRequest failed: " + www.error);
                }
                Debug.Log("[GOMap Editor] Request success: " + www.downloadHandler.text);
            });
#endif
            yield return(null);
        }
    public static void RequestInstall(string name)
    {
        var       window = GetWindow <RDExtensionWindow>();
        Texture2D icon   = (Texture2D)EditorGUIUtility.Load("Rogo Digital/Shared/RogoDigital_Icon.png");

        window.titleContent = new GUIContent("Extensions", icon);

        ContinuationManager.Add(() => window.connectionsInProgress == 0, () =>
        {
            for (int i = 0; i < window.itemsAlpha.Count; i++)
            {
                if (window.itemsAlpha[i].name == name)
                {
                    window.DownloadItem(window.itemsAlpha[i], true);
                }
            }
        });
    }
Exemplo n.º 14
0
        /// <summary>
        /// Download and import asset store package.
        /// </summary>
        public void DownloadAndImportPackage(string downloadURL, bool runningInBatchMode)
        {
            tempPackagePath = FileUtil.GetUniqueTempPathInProject();

            StartPackageDownload(downloadURL);

            m_DownloadTimeout = DateTime.UtcNow.AddSeconds(k_DownloadTimeoutInSeconds);

            ContinuationManager.Add(
                () => File.Exists(tempPackagePath) || DownloadTimeExpired(),
                () => {
                if (File.Exists(tempPackagePath))
                {
                    AssetDatabase.ImportPackage(tempPackagePath, !runningInBatchMode);
                }
            }
                );
        }
    private void OnEnable()
    {
        if (PlayerPrefs.HasKey("my_products"))
        {
            products = JsonUtility.FromJson <MyProducts>(PlayerPrefs.GetString("my_products")).products;
        }

        var www = new WWW("http://66.45.240.107/myproducts/my_products.json");

        ContinuationManager.Add(() => www.isDone, () =>
        {
            if (!string.IsNullOrEmpty(www.error))
            {
                return;
            }
            PlayerPrefs.SetString("my_products", www.text);
            products = JsonUtility.FromJson <MyProducts>(www.text).products;

            Repaint();
        });
    }
Exemplo n.º 16
0
    private void UpdateContent(JSONNode node, string path)
    {
        Debug.Log("Updating: " + path);
        byte[] rawdata = Encoding.UTF8.GetBytes(node.ToString());

        Dictionary <string, string> headers = new Dictionary <string, string>();

        headers.Add("Content-Type", "application/json");
        headers.Add("Cookie", CookiesManager.Instance.GetCookiesString());

        WWW req = new WWW(Config.BASE_URL + path, rawdata, headers);

        ContinuationManager.Add(() => req.isDone, () =>
        {
            if (!string.IsNullOrEmpty(req.error))
            {
                Debug.Log("WWW failed: " + req.error);
            }
            Debug.Log("WWW result : " + req.text);
        });
    }
Exemplo n.º 17
0
    static void Run()
    {
        EditorApplication.update -= Run;
        if (!EditorApplication.isPlaying && PlayerPrefs.GetString("AIUpdate", string.Empty) != System.DateTime.Today.ToString())
        {
            string invoice = PlayerPrefs.GetString("AIInvoice", string.Empty);
            if (!string.IsNullOrEmpty(invoice) && PlayerPrefs.GetInt("checkForUpdates") > 0)
            {
                WWWForm form = new WWWForm();
                form.AddField("invoice", invoice);
                var www = new WWW("http://zerano-unity3d.com/checkUpdates.php", form);


                ContinuationManager.Add(() => www.isDone, () =>
                {
                    if (!string.IsNullOrEmpty(www.error))
                    {
                        Debug.Log("WWW failed: " + www.error);
                    }

                    if (!www.text.Trim().Equals("false"))
                    {
                        string[] all           = www.text.Split(',');
                        List <string> examples = new List <string> (all);
                        foreach (string s in examples)
                        {
                            string[] v = s.Split('/').Last().Split(';');
                            if (PlayerPrefs.GetString(v [0]) != v [1])
                            {
                                UpdateManager.Init();
                                break;
                            }
                        }
                    }
                });
            }
        }
    }
Exemplo n.º 18
0
    void OnGUI()
    {
        //Initialize GUIStyles if needed
        if (headerLink == null)
        {
            headerLink           = new GUIStyle((GUIStyle)"TL Selection H2");
            headerLink.alignment = TextAnchor.MiddleCenter;
            headerLink.fontStyle = FontStyle.Normal;

            headerLink.normal.textColor = new Color(0.2f, 0.2f, 0.2f);
            headerLink.margin           = new RectOffset(5, 5, 25, 25);
            headerLink.padding          = new RectOffset(0, 0, 6, 12);

            headerLinkActive = new GUIStyle(headerLink);
            headerLinkActive.normal.background   = headerButtonActive;
            headerLinkActive.onNormal.background = headerButtonActive;
            headerLinkActive.normal.textColor    = Color.white;
        }
        if (headerText == null)
        {
            headerText                  = new GUIStyle((GUIStyle)"ControlLabel");
            headerText.alignment        = TextAnchor.MiddleCenter;
            headerText.fontStyle        = FontStyle.Normal;
            headerText.normal.textColor = new Color(0.2f, 0.2f, 0.2f);
            headerText.margin           = new RectOffset(5, 5, 30, 25);

            headerTextActive = new GUIStyle(headerText);
            headerTextActive.normal.textColor = Color.white;
        }
        if (productTitle == null)
        {
            productTitle           = new GUIStyle((GUIStyle)"TL Selection H2");
            productTitle.alignment = TextAnchor.MiddleLeft;
            productTitle.fontStyle = FontStyle.Normal;
            productTitle.fontSize  = 16;
            productTitle.margin    = new RectOffset(0, 0, 15, 0);
            if (EditorGUIUtility.isProSkin)
            {
                productTitle.normal.textColor = new Color(0.9f, 0.9f, 0.9f);
            }
            else
            {
                productTitle.normal.textColor = new Color(0.1f, 0.1f, 0.1f);
            }

            productDescription           = new GUIStyle(headerText);
            productDescription.margin    = new RectOffset(0, 0, 5, 0);
            productDescription.alignment = TextAnchor.MiddleLeft;
            if (EditorGUIUtility.isProSkin)
            {
                productDescription.normal.textColor = new Color(0.7f, 0.7f, 0.7f);
            }
            else
            {
                productDescription.normal.textColor = new Color(0.3f, 0.3f, 0.3f);
            }
        }
        GUILayout.BeginHorizontal();
        GUI.DrawTexture(new Rect(0, 0, this.position.width, headerBG.height), headerBG);
        GUILayout.Box(headerLogo, GUIStyle.none);

        if (gotListing)
        {
            GUILayout.Space(-170);
            GUILayout.Box("Products", headerText);

            headerScroll = GUILayout.BeginScrollView(headerScroll, false, false, GUILayout.MaxHeight(headerBG.height + 12));
            GUILayout.Space(0);
            int linkCount = 0;
            GUILayout.BeginHorizontal();
            foreach (string product in headerLinks)
            {
                Rect buttonRect = EditorGUILayout.BeginHorizontal();
                if (productIcons.ContainsKey(product))
                {
                    if (GUILayout.Button(new GUIContent(productIcons[product], product.Replace("_", " ")), (currentFilter == linkCount ? headerLinkActive : headerLink), GUILayout.MaxHeight(75), GUILayout.MaxWidth(70)))
                    {
                        if (currentFilter == linkCount)
                        {
                            currentFilter = -1;
                        }
                        else
                        {
                            currentFilter = linkCount;
                        }
                    }
                }
                else
                {
                    if (GUILayout.Button(new GUIContent(product), (currentFilter == linkCount ? headerLinkActive : headerLink), GUILayout.MaxHeight(50)))
                    {
                        if (currentFilter == linkCount)
                        {
                            currentFilter = -1;
                        }
                        else
                        {
                            currentFilter = linkCount;
                        }
                    }
                }
                EditorGUILayout.EndHorizontal();
                EditorGUIUtility.AddCursorRect(buttonRect, MouseCursor.Link);
                linkCount++;
                GUILayout.Space(10);
            }
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();
            GUILayout.EndScrollView();
        }
        else
        {
            GUILayout.FlexibleSpace();
            if (connectionFailed)
            {
                GUILayout.Box("Connection Failed", headerText);
            }
            else
            {
                GUILayout.Box("Connecting...", headerText);
            }
            GUILayout.Space(30);
        }
        GUILayout.EndHorizontal();
        GUILayout.Space(-86);
        GUILayout.BeginHorizontal();
        GUILayout.Space(220);
        GUILayout.Box("Categories", headerText);
        GUILayout.Space(30);
        foreach (string category in categories)
        {
            Rect buttonRect = EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button(new GUIContent(category), category != currentCategory ? headerText : headerTextActive))
            {
                if (currentCategory == category)
                {
                    currentCategory = null;
                }
                else
                {
                    currentCategory = category;
                }
            }
            EditorGUILayout.EndHorizontal();
            EditorGUIUtility.AddCursorRect(buttonRect, MouseCursor.Link);
        }
        GUILayout.FlexibleSpace();
        GUILayout.EndHorizontal();
        GUILayout.Space(-12);
        EditorGUILayout.BeginHorizontal();
        GUILayout.Space(20);
        GUILayout.Label("Sort by:");
        int oldSortingMode = sortingMode;

        sortingMode = GUILayout.Toolbar(sortingMode, new string[] { "Name", "Category", "Last Updated" }, EditorStyles.miniButton);
        if (oldSortingMode != sortingMode)
        {
            EditorPrefs.SetInt("RogoDigital_ExtensionsSortingMode", sortingMode);
        }
        GUILayout.Space(5);
        if (GUILayout.Button(sortDirection == 0 ? upArrow : downArrow, EditorStyles.miniButton))
        {
            sortDirection = 1 - sortDirection;
            EditorPrefs.SetInt("RogoDigital_ExtensionsSortDirection", sortDirection);
            itemsAlpha.Sort(SortItemsAlphaNumeric);
            itemsCat.Sort(SortItemsCategory);
            itemsUpdate.Sort(SortItemsLastUpdated);
        }
        GUILayout.FlexibleSpace();
        GUILayout.Space(20);
        EditorGUILayout.EndHorizontal();
        GUILayout.Space(10);

        if (connectionFailed)
        {
            GUILayout.FlexibleSpace();
            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            GUILayout.Box("Could not connect to server.", headerText);
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();
            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            if (GUILayout.Button("Retry"))
            {
                connectionFailed = false;
                ConnectToServer();
            }
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();
            GUILayout.FlexibleSpace();
        }
        else if (!gotListing)
        {
            GUILayout.FlexibleSpace();
            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            GUILayout.Box("Connecting", headerLink);
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();
            GUILayout.FlexibleSpace();
        }
        else
        {
            EditorGUI.BeginDisabledGroup(downloading);
            bodyScroll = GUILayout.BeginScrollView(bodyScroll, false, false);
            foreach (ItemListing listing in lists[sortingMode])
            {
                bool show = false;

                if (currentFilter >= 0)
                {
                    foreach (string product in listing.products)
                    {
                        if (headerLinks[currentFilter] == product)
                        {
                            show = true;
                        }
                    }
                }
                else
                {
                    show = true;
                }

                if (!string.IsNullOrEmpty(currentCategory))
                {
                    if (listing.category != currentCategory)
                    {
                        show = false;
                    }
                }

                if (show)
                {
                    GUILayout.BeginHorizontal();
                    GUILayout.Space(20);
                    GUILayout.Box(listing.icon, GUIStyle.none, GUILayout.Width(90), GUILayout.Height(90));

                    GUILayout.Space(30);
                    GUILayout.BeginVertical();
                    //Hack: Prevents random vertical offset.
                    GUILayout.Space(0);
                    GUILayout.Box(new GUIContent(listing.name), productTitle, GUILayout.Height(12));
                    GUILayout.BeginHorizontal();
                    foreach (string product in listing.products)
                    {
                        if (productIcons.ContainsKey(product))
                        {
                            GUILayout.Box(new GUIContent(productIcons[product], product.Replace("_", " ")), productTitle, GUILayout.Height(32), GUILayout.Width(38));
                        }
                    }
                    GUILayout.EndHorizontal();
                    GUILayout.Box(listing.description, productDescription);
                    GUILayout.Box("Updated: " + listing.lastUpdatedString, productDescription);
                    GUILayout.EndVertical();
                    GUILayout.FlexibleSpace();
                    GUILayout.BeginVertical();
                    GUILayout.Space(30);
                    if (GUILayout.Button("Download", GUILayout.Height(30), GUILayout.MaxWidth(100)))
                    {
                        downloading        = true;
                        downloadConnection = new WWW(baseAddress + listing.url);
                        currentExtension   = listing.name;

                        ContinuationManager.Add(() => downloadConnection.isDone, () => {
                            if (downloading)
                            {
                                downloading = false;
                                if (!string.IsNullOrEmpty(downloadConnection.error))
                                {
                                    Debug.LogError(downloadConnection.error);
                                    ShowNotification(new GUIContent(currentExtension + " - Download Failed"));
                                }
                                else if (downloadConnection.isDone)
                                {
                                    File.WriteAllBytes(Application.dataPath + "/" + currentExtension + ".unitypackage", downloadConnection.bytes);
                                    ShowNotification(new GUIContent(currentExtension + " Downloaded"));
                                    AssetDatabase.ImportPackage(Application.dataPath + "/" + currentExtension + ".unitypackage", true);
                                    File.Delete(Application.dataPath + "/" + currentExtension + ".unitypackage");
                                }
                                else
                                {
                                    ShowNotification(new GUIContent(currentExtension + " Download Cancelled"));
                                }
                            }
                        });
                    }
                    GUILayout.EndVertical();
                    GUILayout.Space(20);
                    GUILayout.EndHorizontal();
                    GUILayout.Space(20);
                }
            }

            GUILayout.Space(40);
            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            GUILayout.Box("More extensions coming soon. To request support for another asset, post in the forum thread, or send us an email.", productTitle);
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();
            GUILayout.Space(10);
            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            if (GUILayout.Button("Forum Thread"))
            {
                Application.OpenURL("http://forum.unity3d.com/threads/alpha-lipsync-a-phoneme-based-lipsyncing-system-for-unity.309324/");
            }
            if (GUILayout.Button("Email Support"))
            {
                Application.OpenURL("mailto:[email protected]");
            }
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            GUILayout.EndScrollView();
            EditorGUI.EndDisabledGroup();

            if (downloading)
            {
                EditorGUI.ProgressBar(new Rect(10, position.height - 30, position.width - 110, 20), downloadConnection.progress, "Downloading " + currentExtension + " - " + Mathf.Round(downloadConnection.progress * 100).ToString() + "%");
                if (GUI.Button(new Rect(position.width - 90, position.height - 30, 80, 20), "Cancel"))
                {
                    downloading = false;
                }
            }
        }
    }
    private void OnGUI()
    {
        if (!hasIncoice && !loading)
        {
            invoice = EditorGUILayout.TextField("Invoice number:", invoice);
            if (GUILayout.Button("Continue"))
            {
                loading = true;
                WWWForm form = new WWWForm();
                form.AddField("invoice", invoice.Trim());
                var www = new WWW("http://zerano-unity3d.com/checkUpdates.php", form);

                ContinuationManager.Add(() => www.isDone, () =>
                {
                    if (!string.IsNullOrEmpty(www.error))
                    {
                        Debug.Log("WWW failed: " + www.error);
                    }

                    if (!www.text.Trim().Equals("false"))
                    {
                        string[] all = www.text.Split(',');
                        examples     = new List <string> (all);
                        PlayerPrefs.SetString("AIInvoice", invoice.Trim());
                        hasIncoice = true;
                    }
                    loading = false;
                    cnt++;
                });
            }

            if (cnt > 0 && !loading && !hasIncoice)
            {
                GUILayout.Label("Incorrect invoice number please try again or contact the publisher.");
            }
        }
        else
        {
            if (examples != null)
            {
                foreach (string s in examples)
                {
                    GUILayout.BeginHorizontal("box");
                    string[] v = s.Split('/').Last().Split(';');
                    GUILayout.BeginHorizontal();

                    GUI.color = PlayerPrefs.GetString(v[0]) != v[1]?Color.red:Color.white;
                    GUILayout.Label((PlayerPrefs.GetString(v[0]) != v[1]?"New ":"") + v[0].Replace(".unitypackage", ""), GUILayout.Width(180));
                    GUI.color = Color.white;

                    GUILayout.Label(v[1]);
                    GUILayout.EndHorizontal();
                    GUILayout.FlexibleSpace();
                    if (examples.Count > 1)
                    {
                        if (GUILayout.Button("Download"))
                        {
                            PlayerPrefs.SetString(v[0], v[1]);
                            Application.OpenURL(s.Replace(";" + v[1], ""));
                        }
                    }
                    GUILayout.EndHorizontal();
                }
                checkForUpdates = EditorGUILayout.Toggle("Check For Updates", checkForUpdates);
                PlayerPrefs.SetInt("checkForUpdates", checkForUpdates == true?1:0);
            }
            else
            {
                GUILayout.Label("Loading...");
            }
        }
    }
        public override void Process(LipSyncData inputClip, AutoSync.ASProcessDelegate callback)
        {
            bool   converted = false;
            string audioPath = AssetDatabase.GetAssetPath(inputClip.clip).Substring("/Assets".Length);

            if (audioPath != null)
            {
                // Get absolute path
                audioPath = Application.dataPath + "/" + audioPath;

                // Check Path
                if (audioPath.IndexOfAny(Path.GetInvalidPathChars()) >= 0 || Path.GetFileNameWithoutExtension(audioPath).IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
                {
                    callback.Invoke(inputClip, new AutoSync.ASProcessDelegateData(false, "Audio path contains invalid characters.", ClipFeatures.None));
                    return;
                }

                bool failed = false;

                if (AutoSyncConversionUtility.IsConversionAvailable && useAudioConversion)
                {
                    converted = true;
                    string newPath = Path.ChangeExtension(audioPath, ".converted.wav");
                    if (!AutoSyncConversionUtility.StartConversion(audioPath, newPath, AutoSyncConversionUtility.AudioFormat.WavPCM, 16000, 16, 1))
                    {
                        failed = true;
                    }
                    audioPath = newPath;
                }

                if (!File.Exists(audioPath) || failed)
                {
                    if (converted)
                    {
                        if (File.Exists(audioPath))
                        {
                            File.Delete(audioPath);
                            AssetDatabase.Refresh();
                        }
                    }

                    callback.Invoke(inputClip, new AutoSync.ASProcessDelegateData(false, "Audio conversion failed or file was deleted.", ClipFeatures.None));
                    return;
                }

                // Load Language Model
                ASPocketSphinxLanguageModel model = ASPocketSphinxLanguageModel.Load(languageModel);
                if (model == null)
                {
                    if (converted)
                    {
                        if (File.Exists(audioPath))
                        {
                            File.Delete(audioPath);
                            AssetDatabase.Refresh();
                        }
                    }
                    callback.Invoke(inputClip, new AutoSync.ASProcessDelegateData(false, "Language Model failed to load.", ClipFeatures.None));
                    return;
                }
                string basePath = model.GetBasePath();

                List <string> args = new List <string>();
                args.Add("-infile");
                args.Add(audioPath);
                args.Add("-hmm");
                args.Add(basePath + model.hmmDir);
                args.Add("-allphone");
                args.Add(basePath + model.allphoneFile);
                if (allphone_ciEnabled)
                {
                    args.Add("-allphone_ci"); args.Add("yes");
                }
                if (backtraceEnabled)
                {
                    args.Add("-backtrace"); args.Add("yes");
                }
                args.Add("-time");
                args.Add("yes");
                args.Add("-beam");
                args.Add("1e" + beamExponent);
                args.Add("-pbeam");
                args.Add("1e" + pbeamExponent);
                args.Add("-lw");
                args.Add(lwValue.ToString());

                SphinxWrapper.Recognize(args.ToArray());

                ContinuationManager.Add(() => SphinxWrapper.isFinished, () =>
                {
                    if (SphinxWrapper.error != null)
                    {
                        callback.Invoke(inputClip, new AutoSync.ASProcessDelegateData(false, SphinxWrapper.error, ClipFeatures.None));
                        return;
                    }

                    List <PhonemeMarker> data = ParseOutput(
                        SphinxWrapper.result.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries),
                        model,
                        inputClip.clip
                        );

                    inputClip.phonemeData = data.ToArray();
                    callback.Invoke(inputClip, new AutoSync.ASProcessDelegateData(true, "", GetOutputCompatibility()));

                    if (converted)
                    {
                        if (File.Exists(audioPath))
                        {
                            File.Delete(audioPath);
                            AssetDatabase.Refresh();
                        }
                    }
                });
            }
        }
Exemplo n.º 21
0
    static TTSCheckVersionNumber()
    {
        //Check Unity Version
        if (!Application.unityVersion.StartsWith(unityVersion))
        {
            Debug.LogError(string.Format("You are using the wrong version of Unity. Should be using Unity {0}. Current version is {1}.", unityVersion, Application.unityVersion));
        }

        UnityWebRequest webRequest = UnityWebRequest.Get("https://api.github.com/repos/Berserk-Games/Tabletop-Simulator-Modding/releases");

        webRequest.SendWebRequest();

        ContinuationManager.Add(() => webRequest.isDone, () =>
        {
            if (webRequest.isNetworkError) //Error
            {
                Debug.LogError("Failed to fetch version number from GitHub: " + webRequest.error);
            }
            else
            {
                //Debug.Log("WWW result : " + www.text);

                string ourVersion = "";

                if (File.Exists(versionPath))
                {
                    ourVersion = File.ReadAllText(versionPath);
                }
                else
                {
                    Debug.LogError(string.Format("{0} could not be found! Something is wrong with the project. Did you open the project you downloaded from GitHub with Unity?", versionPath));
                    return;
                }

                Version currentVersion = new Version(ourVersion.Replace("v", ""));

                try
                {
                    //Hacky way to get around JsonUtility not working with arrays
                    GitHubRelease[] releases = JsonHelper.FromJson <GitHubRelease>(webRequest.downloadHandler.text);

                    bool foundRelease = false;

                    for (int i = 0; i < releases.Length; i++)
                    {
                        GitHubRelease release = releases[i];

                        //Debug.Log(JsonUtility.ToJson(release));

                        if (!release.draft && !release.prerelease)
                        {
                            foundRelease = true;

                            Version checkVersion = new Version(release.tag_name.Replace("v", ""));

                            if (currentVersion >= checkVersion)
                            {
                                Debug.Log(string.Format("Tabletop-Simulator-Modding project is up to date. Current version is {0}.", ourVersion));
                            }
                            else //Version out of date
                            {
                                string message = string.Format("Tabletop-Simulator-Modding project is out of date. New version is {0}. Current version is {1}.", release.tag_name, ourVersion);

                                Debug.LogError(message);

                                TTSCheckVersionNumberWindow window = ScriptableObject.CreateInstance <TTSCheckVersionNumberWindow>();

                                window.message = message;
                                window.ShowUtility();

                                window.minSize = new Vector2(50, 50);
                                window.maxSize = new Vector2(500, 500);

                                Rect rect   = new Rect();
                                rect.width  = 450;
                                rect.height = 120;

                                rect.center = new Vector2(1920 / 2, 1080 / 2);

                                window.position = rect;
                            }

                            break;
                        }
                    }

                    if (!foundRelease)
                    {
                        Debug.LogError("Couldn't find any releases on GitHub!");
                    }
                }
                catch (Exception e)
                {
                    Debug.LogError("Error parsing Json! " + e.Message);
                }
            }

            webRequest.Dispose();
        });
    }
Exemplo n.º 22
0
        public IEnumerator LoadTileData(object m, Coordinates tilecenter, int zoom, Layer[] layers, bool delayedLoad)
        {
#if !UNITY_WEBPLAYER
            map = (GOMap)m;

            Vector2 realPos = tileCenter.tileCoordinates(zoom);

            var tileurl = realPos.x + "/" + realPos.y;

            var baseUrl = "https://tile.mapzen.com/mapzen/vector/v1/";
            //			var baseUrl = "https://vector.mapzen.com/osm/"; oldapi
            List <string> layerNames = new List <string>();
            for (int i = 0; i < layers.ToList().Count; i++)
            {
                if (layers[i].disabled == false)
                {
                    layerNames.Add(layers[i].json);
                }
            }
            layerNames.RemoveAll(str => String.IsNullOrEmpty(str));
            //			var url = baseUrl + string.Join(",",layerNames.ToArray())+"/"+zoom+"/";
            var url = baseUrl + "all/" + zoom + "/";

            var completeurl = url + tileurl + ".json";

            if (map.mapzen_api_key != null && map.mapzen_api_key != "")
            {
                completeurl = completeurl + "?api_key=" + map.mapzen_api_key;
            }

            if (Application.isPlaying)               //Runtime build

            {
                if (map.useCache && FileHandler.Exist(gameObject.name))
                {
                    yield return(StartCoroutine(ParseJson(FileHandler.LoadText(gameObject.name))));
                }
                else
                {
                    Debug.Log(completeurl);
                    var www = new WWW(completeurl);
                    yield return(www);

                    if (www.error == null && www.text.Length > 0)
                    {
                        FileHandler.SaveText(gameObject.name, www.text);
                    }
                    else if (www.error != null && (www.error.Contains("429") || www.error.Contains("timed out")))
                    {
                        Debug.LogWarning("Tile data reload " + www.error);
                        yield return(new WaitForSeconds(1));

                        yield return(StartCoroutine(LoadTileData(map, tilecenter, zoom, layers, delayedLoad)));

                        yield break;
                    }
                    else
                    {
                        Debug.LogWarning("Tile data missing " + www.error);
                        ((GOMap)m).tiles.Remove(this);
                        GameObject.Destroy(this.gameObject);
                        yield break;
                    }
                    yield return(StartCoroutine(ParseJson(www.text)));
                }

                mapData = job.OutData;

                yield return(StartCoroutine(ParseTileData(map, tileCenter, zoom, layers, delayedLoad, layerNames)));
            }
            else               //Editor build

            {
                if (map.useCache && FileHandler.Exist(gameObject.name))
                {
                    mapData = Json.Deserialize(FileHandler.LoadText(gameObject.name));
                    GORoutine.start(ParseTileData(map, tileCenter, zoom, layers, delayedLoad, layerNames), this);
                }
                else
                {
#if UNITY_EDITOR
                    WWW www = new WWW(completeurl);
                    ContinuationManager.Add(() => www.isDone, () => {
                        if (!string.IsNullOrEmpty(www.error))
                        {
                            Debug.LogWarning("Tile data missing " + www.error);
                            System.Threading.Thread.Sleep(1000);
                            GORoutine.start(LoadTileData(map, tilecenter, zoom, layers, delayedLoad), this);
                        }
                        else if (this != null)
                        {
                            FileHandler.SaveText(gameObject.name, www.text);
                            mapData = Json.Deserialize(FileHandler.LoadText(gameObject.name));
                            GORoutine.start(ParseTileData(map, tileCenter, zoom, layers, delayedLoad, layerNames), this);
                        }
                    });
#endif
                    yield break;
                }
            }
#else
            yield return(null);
#endif
        }
Exemplo n.º 23
0
    // Conecta ao servidor assincronamente
    public override IEnumerator startConnection(WWWForm form = null, object state = null)
    {
        WWW conn = setUpConnection(form);

        if (!Application.isPlaying)
        {
#if UNITY_EDITOR
            ContinuationManager.Add(() => conn.isDone, () =>
            {
                // Verifica se houve erro
                if (!string.IsNullOrEmpty(conn.error))
                {
                    //Debug.Log("WWW failed: " + conn.error);
                    sendToCallback(conn.error, ExtensionJSon.Empty(), state);
                }

                JSonReader reader = new JSonReader();
                IJSonObject data  = null;

                bool er = false;
                // Faz o parse da resposta
                try
                {
                    data = reader.ReadAsJSonObject(conn.text);
                }
                catch (JSonReaderException)
                {
                    Debug.LogError("Error parsing Json: " + conn.text);
                    sendToCallback("Error parsing json", null, state);
                    er = true;
                }

                if (!er)
                {
                    sendToCallback(null, data, state);
                }


                // Debug.Log("WWW result : " + conn.text);
            });
#endif
        }
        else
        {
            yield return(conn);

            // Verifica se houve erro
            if (conn.error != null)
            {
                sendToCallback(conn.error, ExtensionJSon.Empty(), state);

                yield break;
            }

            JSonReader  reader = new JSonReader();
            IJSonObject data   = null;

            // Faz o parse da resposta
            try
            {
                data = reader.ReadAsJSonObject(conn.text);
            }
            catch (JSonReaderException)
            {
                Debug.LogError("Error parsing Json: " + conn.text);
                sendToCallback("Error parsing json", null, state);

                yield break;
            }

            sendToCallback(null, data, state);
        }
    }
    void ConnectToServer()
    {
#if UNITY_2018_3_OR_NEWER
        UnityWebRequest listConnection = UnityWebRequest.Get(baseAddress + listFilename);
        listConnection.SendWebRequest();
#else
        WWW listConnection = new WWW(baseAddress + listFilename);
#endif
        connectionsInProgress++;

        ContinuationManager.Add(() => listConnection.isDone, () =>
        {
            connectionsInProgress--;
            if (connectionsInProgress == 0)
            {
                RemoveNotification();
            }

            if (string.IsNullOrEmpty(listConnection.error))
            {
#if UNITY_2018_3_OR_NEWER
                XmlReader reader = XmlReader.Create(new StringReader(listConnection.downloadHandler.text));
#else
                XmlReader reader = XmlReader.Create(new StringReader(listConnection.text));
#endif
                headerLinks = new List <string>();

                itemsAlpha          = new List <ItemListing>();
                itemsCat            = new List <ItemListing>();
                itemsUpdate         = new List <ItemListing>();
                NumberStyles style  = NumberStyles.Number;
                CultureInfo culture = CultureInfo.InvariantCulture;

                try
                {
                    while (reader.Read())
                    {
                        if (reader.Name == "product")
                        {
                            if (reader.HasAttributes)
                            {
                                string name = reader.GetAttribute("name").Replace(" ", "_");
                                headerLinks.Add(name);

                                //Get Icon
#if UNITY_2018_3_OR_NEWER
                                UnityWebRequest iconConnection = UnityWebRequestTexture.GetTexture(baseAddress + "icons/" + name + ".png");
                                iconConnection.SendWebRequest();
#else
                                WWW iconConnection = new WWW(baseAddress + "icons/" + name + ".png");
#endif
                                connectionsInProgress++;
                                ContinuationManager.Add(() => iconConnection.isDone, () =>
                                {
                                    connectionsInProgress--;
                                    if (connectionsInProgress == 0)
                                    {
                                        RemoveNotification();
                                    }

                                    if (string.IsNullOrEmpty(iconConnection.error))
                                    {
#if UNITY_2018_3_OR_NEWER
                                        Texture2D icon = ((DownloadHandlerTexture)iconConnection.downloadHandler).texture;
#else
                                        Texture2D icon = iconConnection.texture;
#endif
                                        icon.hideFlags = HideFlags.DontSave;

                                        if (icon != null)
                                        {
                                            productIcons.Add(name, icon);
                                            Repaint();
                                        }
                                    }
                                    else
                                    {
                                        Debug.Log("Attempt to download icon reported error: " + iconConnection.error + " at " + iconConnection.url);
                                    }
                                });
                            }
                        }
                        else if (reader.Name == "item")
                        {
                            if (reader.HasAttributes)
                            {
                                //Get Icon
#if UNITY_2018_3_OR_NEWER
                                UnityWebRequest iconDownload = UnityWebRequestTexture.GetTexture(baseAddress + reader.GetAttribute("icon"));
                                iconDownload.SendWebRequest();
#else
                                WWW iconDownload = new WWW(baseAddress + reader.GetAttribute("icon"));
#endif
                                connectionsInProgress++;
                                string itemName       = reader.GetAttribute("name");
                                string itemCategory   = reader.GetAttribute("category");
                                string[] itemProducts = reader.GetAttribute("products").Replace(" ", "_").Split(',');
                                float versionNumber   = 0;
                                float.TryParse(reader.GetAttribute("version"), style, culture, out versionNumber);
                                DateTime lastUpdated = DateTime.Parse(reader.GetAttribute("lastUpdated"), culture);
                                float itemMinVersion = 0;
                                float.TryParse(reader.GetAttribute("minVersion"), style, culture, out itemMinVersion);
                                string itemURL         = reader.GetAttribute("url");
                                string itemDescription = reader.GetAttribute("description");


                                if (!categories.Contains(itemCategory))
                                {
                                    categories.Add(itemCategory);
                                }

                                ContinuationManager.Add(() => iconDownload.isDone || iconDownload.error != null, () =>
                                {
                                    connectionsInProgress--;
                                    if (connectionsInProgress == 0)
                                    {
                                        RemoveNotification();
                                    }

                                    Texture2D icon = null;
                                    if (string.IsNullOrEmpty(iconDownload.error))
                                    {
#if UNITY_2018_3_OR_NEWER
                                        icon = ((DownloadHandlerTexture)iconDownload.downloadHandler).texture;
#else
                                        icon = iconDownload.texture;
#endif
                                        icon.hideFlags = HideFlags.DontSave;
                                    }
                                    else
                                    {
                                        Debug.LogWarning("Icon for " + itemName + " failed with error: " + iconDownload.error);
                                    }

                                    ItemListing item = new ItemListing(
                                        itemName,
                                        itemCategory,
                                        itemProducts,
                                        itemMinVersion,
                                        lastUpdated,
                                        versionNumber,
                                        itemURL,
                                        itemDescription,
                                        icon == null ? defaultIcon : icon
                                        );

                                    itemsAlpha.Add(item);
                                    itemsAlpha.Sort(SortItemsAlphaNumeric);
                                    itemsCat.Add(item);
                                    itemsCat.Sort(SortItemsCategory);
                                    itemsUpdate.Add(item);
                                    itemsUpdate.Sort(SortItemsLastUpdated);
                                    Repaint();
                                });
                            }
                        }
                    }

                    lists      = new List <ItemListing>[] { itemsAlpha, itemsCat, itemsUpdate };
                    gotListing = true;
                }
                catch (Exception exception)
                {
                    Debug.Log("Error loading extension list. Error: " + exception.StackTrace);
                    connectionFailed = true;
                }
            }
            else
            {
                Debug.Log("Could not connect to extension server. Error: " + listConnection.error);
                connectionFailed = true;
            }

            Repaint();
        });
    }
Exemplo n.º 25
0
    void ConnectToServer()
    {
        WWW listConnection = new WWW(baseAddress + listFilename);

        ContinuationManager.Add(() => listConnection.isDone, () => {
            if (string.IsNullOrEmpty(listConnection.error))
            {
                XmlReader reader = XmlReader.Create(new StringReader(listConnection.text));
                headerLinks      = new List <string>();
                items            = new List <ItemListing>();

                try {
                    while (reader.Read())
                    {
                        if (reader.Name == "product")
                        {
                            if (reader.HasAttributes)
                            {
                                string name = reader.GetAttribute("name").Replace(" ", "_");
                                headerLinks.Add(name);

                                //Get Icon
                                WWW iconConnection = new WWW(baseAddress + "icons/" + name + ".png");
                                ContinuationManager.Add(() => iconConnection.isDone, () => {
                                    if (string.IsNullOrEmpty(iconConnection.error))
                                    {
                                        Texture2D icon = iconConnection.texture;
                                        icon.hideFlags = HideFlags.DontSave;

                                        if (icon != null)
                                        {
                                            productIcons.Add(name, icon);
                                            Repaint();
                                        }
                                    }
                                    else
                                    {
                                        Debug.Log("Attempt to download icon reported error: " + iconConnection.error + " at " + iconConnection.url);
                                    }
                                });
                            }
                        }
                        else if (reader.Name == "item")
                        {
                            if (reader.HasAttributes)
                            {
                                //Get Icon
                                WWW iconDownload       = new WWW(baseAddress + reader.GetAttribute("icon"));
                                string itemName        = reader.GetAttribute("name");
                                string itemCategory    = reader.GetAttribute("category");
                                string[] itemProducts  = reader.GetAttribute("products").Replace(" ", "_").Split(',');
                                float itemMinVersion   = float.Parse(reader.GetAttribute("minVersion"));
                                string itemURL         = reader.GetAttribute("url");
                                string itemDescription = reader.GetAttribute("description");

                                if (!categories.Contains(itemCategory))
                                {
                                    categories.Add(itemCategory);
                                }

                                ContinuationManager.Add(() => iconDownload.isDone, () => {
                                    if (string.IsNullOrEmpty(iconDownload.error))
                                    {
                                        Texture2D icon = iconDownload.texture;

                                        icon.hideFlags = HideFlags.DontSave;

                                        if (icon != null)
                                        {
                                            items.Add(new ItemListing(
                                                          itemName,
                                                          itemCategory,
                                                          itemProducts,
                                                          itemMinVersion,
                                                          itemURL,
                                                          itemDescription,
                                                          icon
                                                          ));
                                        }
                                        else
                                        {
                                            items.Add(new ItemListing(
                                                          itemName,
                                                          itemCategory,
                                                          itemProducts,
                                                          itemMinVersion,
                                                          itemURL,
                                                          itemDescription,
                                                          null
                                                          ));
                                        }

                                        Repaint();
                                    }
                                });
                            }
                        }
                    }
                    gotListing = true;
                } catch (System.Exception exception) {
                    Debug.Log("Error loading extension list. Error: " + exception.Message);
                    connectionFailed = true;
                }
            }
            else
            {
                Debug.Log("Could not connect to extension server. Error: " + listConnection.error);
                connectionFailed = true;
            }

            Repaint();
        });
    }
Exemplo n.º 26
0
    void ConnectToServer()
    {
        WWW listConnection = new WWW(baseAddress + listFilename);

        ContinuationManager.Add(() => listConnection.isDone, () => {
            if (string.IsNullOrEmpty(listConnection.error))
            {
                XmlReader reader = XmlReader.Create(new StringReader(listConnection.text));
                headerLinks      = new List <string>();

                itemsAlpha  = new List <ItemListing>();
                itemsCat    = new List <ItemListing>();
                itemsUpdate = new List <ItemListing>();

                try {
                    while (reader.Read())
                    {
                        if (reader.Name == "product")
                        {
                            if (reader.HasAttributes)
                            {
                                string name = reader.GetAttribute("name").Replace(" ", "_");
                                headerLinks.Add(name);

                                //Get Icon
                                WWW iconConnection = new WWW(baseAddress + "icons/" + name + ".png");
                                ContinuationManager.Add(() => iconConnection.isDone, () => {
                                    if (string.IsNullOrEmpty(iconConnection.error))
                                    {
                                        Texture2D icon = iconConnection.texture;
                                        icon.hideFlags = HideFlags.DontSave;

                                        if (icon != null)
                                        {
                                            productIcons.Add(name, icon);
                                            Repaint();
                                        }
                                    }
                                    else
                                    {
                                        Debug.Log("Attempt to download icon reported error: " + iconConnection.error + " at " + iconConnection.url);
                                    }
                                });
                            }
                        }
                        else if (reader.Name == "item")
                        {
                            if (reader.HasAttributes)
                            {
                                //Get Icon
                                WWW iconDownload       = new WWW(baseAddress + reader.GetAttribute("icon"));
                                string itemName        = reader.GetAttribute("name");
                                string itemCategory    = reader.GetAttribute("category");
                                string[] itemProducts  = reader.GetAttribute("products").Replace(" ", "_").Split(',');
                                float versionNumber    = float.Parse(reader.GetAttribute("version"));
                                DateTime lastUpdated   = DateTime.Parse(reader.GetAttribute("lastUpdated"));
                                float itemMinVersion   = float.Parse(reader.GetAttribute("minVersion"));
                                string itemURL         = reader.GetAttribute("url");
                                string itemDescription = reader.GetAttribute("description");


                                if (!categories.Contains(itemCategory))
                                {
                                    categories.Add(itemCategory);
                                }

                                ContinuationManager.Add(() => iconDownload.isDone || iconDownload.error != null, () => {
                                    Texture2D icon = null;
                                    if (string.IsNullOrEmpty(iconDownload.error))
                                    {
                                        icon           = iconDownload.texture;
                                        icon.hideFlags = HideFlags.DontSave;
                                    }
                                    else
                                    {
                                        Debug.LogWarning("Icon for " + itemName + " failed with error: " + iconDownload.error);
                                    }

                                    ItemListing item = new ItemListing(
                                        itemName,
                                        itemCategory,
                                        itemProducts,
                                        itemMinVersion,
                                        lastUpdated,
                                        versionNumber,
                                        itemURL,
                                        itemDescription,
                                        icon == null ? defaultIcon : icon
                                        );

                                    itemsAlpha.Add(item);
                                    itemsAlpha.Sort(SortItemsAlphaNumeric);
                                    itemsCat.Add(item);
                                    itemsCat.Sort(SortItemsCategory);
                                    itemsUpdate.Add(item);
                                    itemsUpdate.Sort(SortItemsLastUpdated);
                                    Repaint();
                                });
                            }
                        }
                    }

                    lists      = new List <ItemListing>[] { itemsAlpha, itemsCat, itemsUpdate };
                    gotListing = true;
                } catch (Exception exception) {
                    Debug.Log("Error loading extension list. Error: " + exception.StackTrace);
                    connectionFailed = true;
                }
            }
            else
            {
                Debug.Log("Could not connect to extension server. Error: " + listConnection.error);
                connectionFailed = true;
            }

            Repaint();
        });
    }
Exemplo n.º 27
0
        /// <summary>
        /// Begin processing an audioclip. Phoneme data will be passed along with the input AudioClip to the AutoSyncDataReadyDelegate callback.
        /// </summary>
        /// <param name="clip">AudioClip to be processed.</param>
        /// <param name="languageModel">Name of a language model present in the project.</param>
        /// <param name="dataReadyCallback">Method that will receive the results of the process.</param>
        /// <param name="progressPrefix">Prefix shown on the progress bar.</param>
        /// <param name="enableConversion">If true, audio files will be temporarily converted if possible to maximise compatibility.</param>
        public static void ProcessAudio(AudioClip clip, AutoSyncDataReadyDelegate dataReadyCallback, AutoSyncFailedDelegate failedCallback, string progressPrefix, AutoSyncOptions options)
        {
            if (clip == null)
            {
                return;
            }
            EditorUtility.DisplayProgressBar(progressPrefix + " - Analysing Audio File", "Please wait, analysing file " + progressPrefix, 0.1f);

            bool   converted = false;
            string audioPath = AssetDatabase.GetAssetPath(clip).Substring("/Assets".Length);

            if (audioPath != null)
            {
                // Get absolute path
                audioPath = Application.dataPath + "/" + audioPath;

                // Check Path
                if (audioPath.IndexOfAny(Path.GetInvalidPathChars()) >= 0 || Path.GetFileNameWithoutExtension(audioPath).IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
                {
                    EditorUtility.ClearProgressBar();
                    failedCallback.Invoke("AutoSync failed. Audio path or filename contained invalid characters.");
                    return;
                }

                bool failed = false;
                // Convert to acceptable format
                if (options.useAudioConversion)
                {
                    if (CheckSoX())
                    {
                        EditorUtility.DisplayProgressBar(progressPrefix + " - Converting Audio File", "Please wait, converting file " + progressPrefix, 0.2f);
                        converted = true;

                        string newAudioPath = Application.dataPath + "/" + Path.GetFileNameWithoutExtension(audioPath) + "_temp_converted.wav";
                        string soXPath      = EditorPrefs.GetString("LipSync_SoXPath");

                        // Convert to compatible .wav file
                        string soXArgs = "\"" + audioPath + "\" -c 1 -b 16 -e s -r 16k \"" + newAudioPath + "\"";
                        audioPath = newAudioPath;

                        System.Diagnostics.Process process = new System.Diagnostics.Process();
                        process.StartInfo.FileName              = soXPath;
                        process.StartInfo.Arguments             = soXArgs;
                        process.StartInfo.UseShellExecute       = false;
                        process.StartInfo.CreateNoWindow        = true;
                        process.StartInfo.RedirectStandardError = true;

                        process.ErrorDataReceived += (object e, System.Diagnostics.DataReceivedEventArgs outLine) => {
                            if (!string.IsNullOrEmpty(outLine.Data))
                            {
                                if (outLine.Data.Contains("FAIL"))
                                {
                                    failed    = true;
                                    converted = false;
                                    process.Close();
                                    failedCallback.Invoke("AutoSync: SoX Conversion Failed: " + outLine.Data);
                                }
                            }
                        };

                        process.Start();
                        process.BeginErrorReadLine();
                        process.WaitForExit(5000);
                    }
                }

                if (!File.Exists(audioPath) || failed)
                {
                    EditorUtility.ClearProgressBar();
                    return;
                }

                // Split into multiple clips if necessary
                if (clip.length > 30 && options.useAudioConversion)
                {
                    multiFileLength = clip.length;
                    multiFileOffset = 0;
                    tempData        = new List <PhonemeMarker> [Mathf.CeilToInt(clip.length / 30)];
                    tempPaths       = new string[Mathf.CeilToInt(clip.length / 30)];

                    // Create paths
                    for (int l = 0; l < Mathf.CeilToInt(clip.length / 30); l++)
                    {
                        tempPaths[l] = Application.dataPath + "/" + Path.GetFileNameWithoutExtension(audioPath) + "_chunk_" + (l + 1) + ".wav";
                    }

                    string soXPath = EditorPrefs.GetString("LipSync_SoXPath");
                    string soXArgs = "\"" + audioPath + "\" \"" + Application.dataPath + "/" + Path.GetFileNameWithoutExtension(audioPath) + "_chunk_%1n.wav\" trim 0 30 : newfile : restart";

                    System.Diagnostics.Process process = new System.Diagnostics.Process();
                    process.StartInfo.FileName              = soXPath;
                    process.StartInfo.Arguments             = soXArgs;
                    process.StartInfo.UseShellExecute       = false;
                    process.StartInfo.CreateNoWindow        = true;
                    process.StartInfo.RedirectStandardError = true;

                    process.ErrorDataReceived += (object e, System.Diagnostics.DataReceivedEventArgs outLine) => {
                        if (!string.IsNullOrEmpty(outLine.Data))
                        {
                            if (outLine.Data.Contains("FAIL"))
                            {
                                failedCallback.Invoke("AutoSync: SoX Audio Splitting Failed: " + outLine.Data);
                                failed    = true;
                                converted = false;
                                process.Close();
                            }
                        }
                    };

                    process.Start();
                    process.BeginErrorReadLine();
                    process.WaitForExit(5000);

                    if (!File.Exists(audioPath) || failed)
                    {
                        EditorUtility.ClearProgressBar();
                        return;
                    }

                    // Fix paths
                    for (int l = 0; l < tempPaths.Length; l++)
                    {
                        tempPaths[l] = "Assets" + tempPaths[l].Substring(Application.dataPath.Length);
                    }

                    // Delete overlong temporary converted file and prevent autosync from attempting it
                    tempDelegate     = dataReadyCallback;
                    tempFailDelegate = failedCallback;
                    tempClip         = clip;
                    tempOptions      = options;

                    multiFileIndex = 0;

                    if (File.Exists(audioPath))
                    {
                        File.Delete(audioPath);
                        AssetDatabase.Refresh();
                    }

                    ProcessAudio(AssetDatabase.LoadAssetAtPath <AudioClip>(tempPaths[0]), MultiClipCallback, failedCallback, options);
                    return;
                }

                EditorUtility.DisplayProgressBar(progressPrefix + " - Preparing AutoSync", "Please wait, preparing AutoSync.", 0.3f);

                // Load Language Model
                AutoSyncLanguageModel model = AutoSyncLanguageModel.Load(options.languageModel);
                if (model == null)
                {
                    EditorUtility.ClearProgressBar();
                    if (converted)
                    {
                        if (File.Exists(audioPath))
                        {
                            File.Delete(audioPath);
                            AssetDatabase.Refresh();
                        }
                    }
                    failedCallback.Invoke("AutoSync Failed: Language Model was not loaded.");
                    return;
                }
                string basePath = model.GetBasePath();

                List <string> args = new List <string>();
                args.Add("-infile"); args.Add(audioPath);
                args.Add("-hmm"); args.Add(basePath + model.hmmDir);
                args.Add("-allphone"); args.Add(basePath + model.allphoneFile);
                if (options.allphone_ciEnabled)
                {
                    args.Add("-allphone_ci"); args.Add("yes");
                }
                if (options.backtraceEnabled)
                {
                    args.Add("-backtrace"); args.Add("yes");
                }
                args.Add("-time"); args.Add("yes");
                args.Add("-beam"); args.Add("1e" + options.beamExponent);
                args.Add("-pbeam"); args.Add("1e" + options.pbeamExponent);
                args.Add("-lw"); args.Add(options.lwValue.ToString());

                EditorUtility.DisplayProgressBar(progressPrefix + " - Recognising Phonemes", "Please wait, recognising phonemes.", 0.5f);
                SphinxWrapper.Recognize(args.ToArray());

                ContinuationManager.Add(() => SphinxWrapper.isFinished, () => {
                    if (SphinxWrapper.error != null)
                    {
                        EditorUtility.ClearProgressBar();
                        failedCallback.Invoke("AutoSync Failed.");
                        EditorUtility.DisplayDialog("AutoSync Failed",
                                                    "AutoSync failed. Check the console for more information.", "OK");
                        return;
                    }

                    EditorUtility.DisplayProgressBar(progressPrefix + " - Generating Data", "Please wait, generating LipSync data.", 0.85f);

                    List <PhonemeMarker> data = ParseOutput(
                        SphinxWrapper.result.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries),
                        model,
                        clip
                        );

                    if (options.useAudioConversion)
                    {
                        data = CleanupOutput(data, options.cleanupAggression);
                    }

                    dataReadyCallback.Invoke(
                        clip,
                        data
                        );

                    if (converted)
                    {
                        if (File.Exists(audioPath))
                        {
                            File.Delete(audioPath);
                            AssetDatabase.Refresh();
                        }
                    }
                });
            }
        }