//don't even try exporting the scene. just generate the folder and json file
        public static void ExportSceneAR()
        {
            string fullName = UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().name;
            string objPath  = CognitiveVR_SceneExplorerExporter.GetDirectory(fullName);

            //if folder exists, delete mtl, obj, png and json contents
            if (Directory.Exists(objPath))
            {
                var files = Directory.GetFiles(objPath);
                for (int i = 0; i < files.Length; i++)
                {
                    File.Delete(files[i]);
                }
            }

            //write json settings file
            string jsonSettingsContents = "{ \"scale\":1,\"sceneName\":\"" + fullName + "\",\"sdkVersion\":\"" + Core.SDK_VERSION + "\"}";

            File.WriteAllText(objPath + "settings.json", jsonSettingsContents);
        }
Example #2
0
        public static void ExportScene(bool includeTextures)
        {
            string fullName = UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().name + appendName;

            CognitiveVR_SceneExplorerExporter.ExportWholeSelectionToSingle(fullName, includeTextures);


            if (string.IsNullOrEmpty(prefs.SavedBlenderPath) || !prefs.SavedBlenderPath.ToLower().EndsWith("blender.exe"))
            {
                Debug.LogError("Blender.exe is not found during scene export! Use Edit>Preferences...CognitivePreferences to locate Blender.exe\nScene: " + fullName + " exported to folder but not mesh decimated!");
                return;
            }

            string objPath            = CognitiveVR_SceneExplorerExporter.GetDirectory(fullName);
            string decimateScriptPath = Application.dataPath + "/CognitiveVR/Editor/decimateall.py";


            //System.Diagnostics.Process.Start("http://google.com/search?q=" + "cat pictures");

            decimateScriptPath = decimateScriptPath.Replace(" ", "\" \"");
            objPath            = objPath.Replace(" ", "\" \"");
            fullName           = fullName.Replace(" ", "\" \"");

            EditorUtility.ClearProgressBar();


            ProcessStartInfo ProcessInfo;

            ProcessInfo = new ProcessStartInfo(prefs.SavedBlenderPath);
            ProcessInfo.UseShellExecute = true;
            ProcessInfo.Arguments       = "-P " + decimateScriptPath + " " + objPath + " " + prefs.ExplorerMinimumFaceCount + " " + prefs.ExplorerMaximumFaceCount + " " + fullName;

            //KNOWN BUG - changing scene while blender is decimating the level will break the file that should be uploaded
            Process.Start(ProcessInfo);
            BlenderRequest            = true;
            HasOpenedBlender          = false;
            EditorApplication.update += UpdateProcess;
        }
        /// <summary>
        /// export selected gameobjects, temporarily spawn them in the scene if they are prefabs
        /// </summary>
        /// <returns>true if exported at least 1 mesh</returns>
        public static bool ExportSelectedObjectsPrefab()
        {
            List <Transform> entireSelection = new List <Transform>();

            entireSelection.AddRange(Selection.GetTransforms(SelectionMode.Editable));

            if (entireSelection.Count == 0)
            {
                Debug.Log("No Dynamic Objects selected"); return(false);
            }

            Debug.Log("Starting export of " + entireSelection.Count + " Dynamic Objects");

            List <Transform> sceneObjects = new List <Transform>();

            sceneObjects.AddRange(Selection.GetTransforms(SelectionMode.Editable | SelectionMode.ExcludePrefab));

            List <Transform> prefabsToSpawn = new List <Transform>();

            //add prefab objects to a list
            foreach (var v in entireSelection)
            {
                if (!sceneObjects.Contains(v))
                {
                    prefabsToSpawn.Add(v);
                }
            }

            //spawn prefabs
            var temporarySpawnedPrefabs = new List <GameObject>();

            foreach (var v in prefabsToSpawn)
            {
                var newPrefab = GameObject.Instantiate(v.gameObject);
                temporarySpawnedPrefabs.Add(newPrefab);
                sceneObjects.Add(newPrefab.transform);
            }

            //export all the objects
            int           successfullyExportedCount = 0;
            List <string> exportedMeshNames         = new List <string>();
            List <string> totalExportedMeshNames    = new List <string>();

            foreach (var v in sceneObjects)
            {
                var dynamic = v.GetComponent <DynamicObject>();
                if (dynamic == null)
                {
                    continue;
                }

                if (!dynamic.UseCustomMesh)
                {
                    //skip exporting a mesh with no name
                    continue;
                }
                if (string.IsNullOrEmpty(dynamic.MeshName))
                {
                    if (!totalExportedMeshNames.Contains(""))
                    {
                        totalExportedMeshNames.Add("");
                    }
                    Debug.LogWarning("GameObject " + dynamic.gameObject + " has empty mesh name");
                    continue;
                }

                if (exportedMeshNames.Contains(dynamic.MeshName))
                {
                    successfullyExportedCount++; continue;
                }                                                                                            //skip exporting same mesh

                if (v.GetComponent <Canvas>() != null)
                {
                    //TODO merge this deeper in the export process. do this recurively ignoring child dynamics
                    //take a snapshot
                    var width  = v.GetComponent <RectTransform>().sizeDelta.x *v.localScale.x;
                    var height = v.GetComponent <RectTransform>().sizeDelta.y *v.localScale.y;

                    var screenshot = CognitiveVR_SceneExplorerExporter.Snapshot(v);

                    var mesh = CognitiveVR_SceneExplorerExporter.ExportQuad(dynamic.MeshName, width, height, v, UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().name, screenshot);
                    CognitiveVR_SceneExplorerExporter.ExportDynamicObject(mesh, dynamic.MeshName, screenshot, dynamic.MeshName);
                    EditorCore.SaveDynamicThumbnailAutomatic(dynamic.gameObject);
                    successfullyExportedCount++;
                }
                else if (CognitiveVR_SceneExplorerExporter.ExportDynamicObject(v))
                {
                    EditorCore.SaveDynamicThumbnailAutomatic(dynamic.gameObject);
                    successfullyExportedCount++;
                }

                foreach (var common in System.Enum.GetNames(typeof(DynamicObject.CommonDynamicMesh)))
                {
                    if (common.ToLower() == dynamic.MeshName.ToLower())
                    {
                        //don't export common meshes!
                        continue;
                    }
                }
                if (!totalExportedMeshNames.Contains(dynamic.MeshName))
                {
                    totalExportedMeshNames.Add(dynamic.MeshName);
                }
                if (!exportedMeshNames.Contains(dynamic.MeshName))
                {
                    exportedMeshNames.Add(dynamic.MeshName);
                }
            }

            //destroy the temporary prefabs
            foreach (var v in temporarySpawnedPrefabs)
            {
                GameObject.DestroyImmediate(v);
            }

            if (entireSelection.Count == 0)
            {
                EditorUtility.DisplayDialog("Dynamic Object Export", "No Dynamic Objects selected", "Ok");
                return(false);
            }

            if (successfullyExportedCount == 0)
            {
                EditorUtility.DisplayDialog("Dynamic Object Export", "No Dynamic Objects successfully exported.\n\nDo you have Mesh Renderers, Skinned Mesh Renderers or Canvas components attached or as children?", "Ok");
                return(false);
            }

            if (successfullyExportedCount == 1 && entireSelection.Count == 1)
            {
                EditorUtility.DisplayDialog("Dynamic Object Export", "Successfully exported 1 Dynamic Object mesh", "Ok");
            }
            else
            {
                EditorUtility.DisplayDialog("Dynamic Object Export", "From selected Dynamic Objects , found " + totalExportedMeshNames.Count + " unique mesh names and successfully exported " + successfullyExportedCount, "Ok");
            }
            return(true);
        }
        /// <summary>
        /// export all dynamic objects in scene. skip prefabs
        /// </summary>
        /// <returns>true if any dynamics are exported</returns>
        public static bool ExportAllDynamicsInScene()
        {
            //List<Transform> entireSelection = new List<Transform>();
            //entireSelection.AddRange(Selection.GetTransforms(SelectionMode.Editable));

            var dynamics = FindObjectsOfType <DynamicObject>();

            Debug.Log("Starting export of " + dynamics.Length + " Dynamic Objects");


            //export all the objects
            int           successfullyExportedCount = 0;
            List <string> exportedMeshNames         = new List <string>();
            List <string> totalExportedMeshNames    = new List <string>();

            foreach (var dynamic in dynamics)
            {
                if (!dynamic.UseCustomMesh)
                {
                    //skip exporting a mesh with no name
                    continue;
                }
                if (string.IsNullOrEmpty(dynamic.MeshName))
                {
                    if (!totalExportedMeshNames.Contains(""))
                    {
                        totalExportedMeshNames.Add("");
                    }
                    Debug.LogWarning("GameObject " + dynamic.gameObject + " has empty mesh name");
                    continue;
                }

                if (exportedMeshNames.Contains(dynamic.MeshName))
                {
                    successfullyExportedCount++; continue;
                }                                                                                            //skip exporting same mesh

                if (dynamic.GetComponent <Canvas>() != null)
                {
                    //TODO merge this deeper in the export process. do this recurively ignoring child dynamics
                    //take a snapshot
                    var width  = dynamic.GetComponent <RectTransform>().sizeDelta.x *dynamic.transform.localScale.x;
                    var height = dynamic.GetComponent <RectTransform>().sizeDelta.y *dynamic.transform.localScale.y;

                    var screenshot = CognitiveVR_SceneExplorerExporter.Snapshot(dynamic.transform);

                    var mesh = CognitiveVR_SceneExplorerExporter.ExportQuad(dynamic.MeshName, width, height, dynamic.transform, UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().name, screenshot);
                    CognitiveVR_SceneExplorerExporter.ExportDynamicObject(mesh, dynamic.MeshName, screenshot, dynamic.MeshName);
                    EditorCore.SaveDynamicThumbnailAutomatic(dynamic.gameObject);
                    successfullyExportedCount++;
                }
                else if (CognitiveVR_SceneExplorerExporter.ExportDynamicObject(dynamic.transform))
                {
                    EditorCore.SaveDynamicThumbnailAutomatic(dynamic.gameObject);
                    successfullyExportedCount++;
                }

                foreach (var common in System.Enum.GetNames(typeof(DynamicObject.CommonDynamicMesh)))
                {
                    if (common.ToLower() == dynamic.MeshName.ToLower())
                    {
                        //don't export common meshes!
                        continue;
                    }
                }
                if (!totalExportedMeshNames.Contains(dynamic.MeshName))
                {
                    totalExportedMeshNames.Add(dynamic.MeshName);
                }

                if (!exportedMeshNames.Contains(dynamic.MeshName))
                {
                    exportedMeshNames.Add(dynamic.MeshName);
                }
            }

            if (successfullyExportedCount == 0)
            {
                EditorUtility.DisplayDialog("Dynamic Object Export", "No Dynamic Objects successfully exported.\n\nDo you have Mesh Renderers, Skinned Mesh Renderers or Canvas components attached or as children?", "Ok");
                return(false);
            }

            EditorUtility.DisplayDialog("Dynamic Object Export", "From all Dynamic Objects in scene, found " + totalExportedMeshNames.Count + " unique mesh names and successfully exported " + successfullyExportedCount, "Ok");
            return(true);
        }
        public static void UploadDecimatedScene(CognitiveVR_Preferences.SceneSettings settings, System.Action uploadComplete)
        {
            //if uploadNewScene POST
            //else PUT to sceneexplorer/sceneid

            if (settings == null)
            {
                UploadSceneSettings = null; return;
            }

            UploadSceneSettings = settings;

            bool hasExistingSceneId = settings != null && !string.IsNullOrEmpty(settings.SceneId);

            bool   uploadConfirmed = false;
            string sceneName       = settings.SceneName;

            string[] filePaths = new string[] { };

            string sceneExportDirectory = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "CognitiveVR_SceneExplorerExport" + Path.DirectorySeparatorChar + settings.SceneName + Path.DirectorySeparatorChar;
            var    SceneExportDirExists = Directory.Exists(sceneExportDirectory);

            if (SceneExportDirExists)
            {
                filePaths = Directory.GetFiles(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "CognitiveVR_SceneExplorerExport" + Path.DirectorySeparatorChar + sceneName + Path.DirectorySeparatorChar);
            }

            //custom confirm upload popup windows
            if ((!SceneExportDirExists || filePaths.Length <= 1))
            {
                if (EditorUtility.DisplayDialog("Upload Scene", "Scene " + settings.SceneName + " has no exported geometry. Upload anyway?", "Yes", "No"))
                {
                    uploadConfirmed = true;
                    //create a json.settings file in the directory
                    string objPath = CognitiveVR_SceneExplorerExporter.GetDirectory(sceneName);

                    Directory.CreateDirectory(objPath);

                    string jsonSettingsContents = "{ \"scale\":1, \"sceneName\":\"" + settings.SceneName + "\",\"sdkVersion\":\"" + Core.SDK_VERSION + "\"}";
                    File.WriteAllText(objPath + "settings.json", jsonSettingsContents);
                }
            }
            else
            {
                uploadConfirmed = true;

                /*if (EditorUtility.DisplayDialog("Upload Scene", "Do you want to upload \"" + settings.SceneName + "\" to your Dashboard?", "Yes", "No"))
                 * {
                 *
                 * }*/
            }

            if (!uploadConfirmed)
            {
                UploadSceneSettings = null;
                return;
                //just exit now
            }

            //after confirmation because uploading an empty scene creates a settings.json file
            if (Directory.Exists(sceneExportDirectory))
            {
                filePaths = Directory.GetFiles(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "CognitiveVR_SceneExplorerExport" + Path.DirectorySeparatorChar + sceneName + Path.DirectorySeparatorChar);
            }

            string[] screenshotPath = new string[0];
            if (Directory.Exists(sceneExportDirectory + "screenshot"))
            {
                screenshotPath = Directory.GetFiles(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "CognitiveVR_SceneExplorerExport" + Path.DirectorySeparatorChar + sceneName + Path.DirectorySeparatorChar + "screenshot");
            }
            else
            {
                Debug.Log("SceneExportWindow Upload can't find directory to screenshot");
            }

            string fileList = "Upload Files:\n";

            string mtlFilepath = "";
            string objFilepath = "";

            WWWForm wwwForm = new WWWForm();

            foreach (var f in filePaths)
            {
                if (f.ToLower().EndsWith(".ds_store"))
                {
                    Debug.Log("skip file " + f);
                    continue;
                }

                //set obj file. prefer decimated
                if (f.EndsWith(".obj"))
                {
                    if (f.EndsWith("_decimated.obj"))
                    {
                        objFilepath = f;
                    }
                    else if (string.IsNullOrEmpty(objFilepath))
                    {
                        objFilepath = f;
                    }
                    continue;
                }

                //set mtl file. prefer decimated
                if (f.EndsWith(".mtl"))
                {
                    if (f.EndsWith("_decimated.mtl"))
                    {
                        mtlFilepath = f;
                    }
                    else if (string.IsNullOrEmpty(mtlFilepath))
                    {
                        mtlFilepath = f;
                    }
                    continue;
                }

                fileList += f + "\n";

                var data = File.ReadAllBytes(f);
                wwwForm.AddBinaryData("file", data, Path.GetFileName(f));
            }

            if (!string.IsNullOrEmpty(objFilepath))
            {
                //add obj and mtl files
                wwwForm.AddBinaryData("file", File.ReadAllBytes(objFilepath), Path.GetFileName(objFilepath));
                fileList += objFilepath + "\n";
                wwwForm.AddBinaryData("file", File.ReadAllBytes(mtlFilepath), Path.GetFileName(mtlFilepath));
                fileList += mtlFilepath + "\n";
            }

            Debug.Log(fileList);

            if (screenshotPath.Length == 0)
            {
                Debug.Log("SceneExportWindow Upload can't find files in screenshot directory");
            }
            else
            {
                wwwForm.AddBinaryData("screenshot", File.ReadAllBytes(screenshotPath[0]), "screenshot.png");
            }

            if (hasExistingSceneId) //upload new verison of existing scene
            {
                Dictionary <string, string> headers = new Dictionary <string, string>();
                if (EditorCore.IsDeveloperKeyValid)
                {
                    headers.Add("Authorization", "APIKEY:DEVELOPER " + EditorCore.DeveloperKey);
                    //headers.Add("Content-Type", "multipart/form-data; boundary=\""+)
                    foreach (var v in wwwForm.headers)
                    {
                        headers[v.Key] = v.Value;
                    }
                }
                EditorNetwork.Post(Constants.POSTUPDATESCENE(settings.SceneId), wwwForm.data, PostSceneUploadResponse, headers, true, "Upload", "Uploading new version of scene");//AUTH
            }
            else //upload as new scene
            {
                //posting wwwform with headers


                //sceneUploadWWW = new WWW(Constants.POSTNEWSCENE(), wwwForm);
                Dictionary <string, string> headers = new Dictionary <string, string>();
                if (EditorCore.IsDeveloperKeyValid)
                {
                    headers.Add("Authorization", "APIKEY:DEVELOPER " + EditorCore.DeveloperKey);
                    //headers.Add("Content-Type", "multipart/form-data; boundary=\""+)
                    foreach (var v in wwwForm.headers)
                    {
                        headers[v.Key] = v.Value;
                    }
                }
                EditorNetwork.Post(Constants.POSTNEWSCENE(), wwwForm.data, PostSceneUploadResponse, headers, true, "Upload", "Uploading new scene");//AUTH
                //Debug.Log("Upload new scene");
            }

            UploadComplete = uploadComplete;
            //EditorApplication.update += UpdateUploadData;
        }
        //export and try to decimate the scene
        public static void ExportScene(bool includeTextures, bool staticGeometry, float minSize, int textureDivisor, string developerkey, string texturename)
        {
            if (blenderProcess != null)
            {
                Debug.LogError("Currently decimating a scene. Please wait until this is finished!");
                return;
            }

            if (UploadSceneSettings != null)
            {
                Debug.LogError("Currently uploading a scene. Please wait until this is finished!");
                return;
            }

            string fullName = UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().name;

            //export scene from unity
            bool successfulExport = CognitiveVR_SceneExplorerExporter.ExportScene(fullName, includeTextures, staticGeometry, minSize, textureDivisor, texturename);

            string objPath = CognitiveVR_SceneExplorerExporter.GetDirectory(fullName);

            //write json settings file
            string jsonSettingsContents = "{ \"scale\":1,\"sceneName\":\"" + fullName + "\",\"sdkVersion\":\"" + Core.SDK_VERSION + "\"}";

            File.WriteAllText(objPath + "settings.json", jsonSettingsContents);

            if (!successfulExport)
            {
                Debug.LogError("Scene export failed!");
                return;
            }

            //begin scene decimation
            if (!EditorCore.IsBlenderPathValid)
            {
                Debug.LogWarning("Blender not found during scene export. May result in large files uploaded to Scene Explorer");
                return;
            }

            string filepath = "";

            if (!EditorCore.RecursiveDirectorySearch("", out filepath, "CognitiveVR" + System.IO.Path.DirectorySeparatorChar + "Editor"))
            {
                Debug.LogError("Could not find CognitiveVR/Editor/decimateall.py");
            }

            string decimateScriptPath = filepath + System.IO.Path.DirectorySeparatorChar + "decimateall.py";

            decimateScriptPath = decimateScriptPath.Replace(" ", "\" \"");
            objPath            = objPath.Replace(" ", "\" \"");
            fullName           = fullName.Replace(" ", "\" \"");

            EditorUtility.ClearProgressBar();

            ProcessStartInfo processInfo;

#if UNITY_EDITOR_WIN
            processInfo = new ProcessStartInfo(EditorCore.BlenderPath);
            processInfo.UseShellExecute = true;
            processInfo.Arguments       = "-P " + decimateScriptPath + " " + objPath + " " + EditorCore.ExportSettings.ExplorerMinimumFaceCount + " " + EditorCore.ExportSettings.ExplorerMaximumFaceCount + " " + fullName;
#elif UNITY_EDITOR_OSX
            processInfo                 = new ProcessStartInfo("open");
            processInfo.Arguments       = EditorCore.BlenderPath + " --args -P " + decimateScriptPath + " " + objPath + " " + EditorCore.ExportSettings.ExplorerMinimumFaceCount + " " + EditorCore.ExportSettings.ExplorerMaximumFaceCount + " " + fullName;
            processInfo.UseShellExecute = false;
#endif

            //changing scene while blender is decimating the level will break the file that will be automatically uploaded
            blenderProcess            = Process.Start(processInfo);
            BlenderRequest            = true;
            HasOpenedBlender          = false;
            EditorApplication.update += UpdateProcess;
            UploadSceneSettings       = CognitiveVR_Preferences.FindCurrentScene();

            blenderStartTime = (float)EditorApplication.timeSinceStartup;
        }