Пример #1
0
    public static void LoadMesh()
    {
        // Master client will load mesh from disk
        if (Type == DeviceType.MasterClient)
        {
            _mesh = SimpleMeshSerializer.Serialize(MeshSaver.Load("RoomMesh"));
        }
        // HoloLens will scan the room and creates mesh
        else if (Type == DeviceType.HoloLens)
        {
            // The following code is copying from UWB-ARSandbox/Assets/Scripts/netWorkManager.cs:sendMeshToUnity()
            List <MeshFilter> meshFilters = MappingManager.GetMeshFilters();
            List <Mesh>       meshes      = new List <Mesh>();

            foreach (var meshFilter in meshFilters)
            {
                Mesh           mesh  = meshFilter.sharedMesh;
                Mesh           clone = new Mesh();
                List <Vector3> verts = new List <Vector3>();
                verts.AddRange(mesh.vertices);

                for (int i = 0; i < verts.Count; i++)
                {
                    verts[i] = meshFilter.transform.TransformPoint(verts[i]);
                }

                clone.SetVertices(verts);
                clone.SetTriangles(mesh.triangles, 0);
                meshes.Add(clone);
            }

            _mesh = SimpleMeshSerializer.Serialize(meshes);
        }
    }
Пример #2
0
 public static void SaveMesh()
 {
     if (Type == DeviceType.MasterClient)
     {
         MeshSaver.Save("RoomMesh", SimpleMeshSerializer.Deserialize(_mesh));
     }
 }
Пример #3
0
    // Start is called before the first frame update
    void Start()
    {
        ObjImporter newMesh    = new ObjImporter();
        Mesh        holderMesh = newMesh.ImportFile("/home/sourabh/Documents/TU-Berlin/Thesis/Sytheticdata/ml-imagesynthesis/Assets/CADPictures/PandaMale.obj");

        MeshSaver.SaveMesh(holderMesh, "PandaMale");
    }
        public static void ExportRoomToWavefront()
        {
            string selectedFile = EditorUtility.OpenFilePanelWithFilters("Select Room File", MeshSaver.MeshFolderName, new string[] { "Room", "room" });

            if (string.IsNullOrEmpty(selectedFile))
            {
                return;
            }

            string             fileName = Path.GetFileNameWithoutExtension(selectedFile);
            IEnumerable <Mesh> meshes   = null;

            try
            {
                meshes = MeshSaver.Load(fileName);
            }
            catch
            {
                // Handling exceptions, and null returned by MeshSaver.Load, by checking if meshes
                // is still null below.
            }

            if (meshes == null)
            {
                EditorUtility.DisplayDialog(ExportDialogErrorTitle, "Unable to parse selected file.", "Ok");
                return;
            }

            SaveMeshesToWavefront(fileName, meshes);

            // Open the location on where the mesh was saved.
            System.Diagnostics.Process.Start(ExportDirectory);
        }
Пример #5
0
        static void ConvertMesh(string src, string dstFolder)
        {
            GameObject go = AssetDatabase.LoadAssetAtPath <GameObject> (src);

            if (go != null)
            {
                // 输出骨架
                ByteBuffer bfSkeleton = SkeletonSaver.Save(go);
                FileSaver.Save(bfSkeleton, Context.Skeletons, dstFolder + "/skeleton.doub");

                // 输出网格
                SkinnedMeshRenderer[] smrs = go.GetComponentsInChildren <SkinnedMeshRenderer> ();
                for (int i = 0; i < smrs.Length; i++)
                {
                    string nameMesh = System.IO.Path.GetFileNameWithoutExtension(src);
                    if (smrs.Length > 1)
                    {
                        nameMesh = smrs[i].sharedMesh.name + "@" + nameMesh;
                    }

                    ByteBuffer bfMesh = MeshSaver.Save(smrs[i].sharedMesh, smrs[i].bones);
                    FileSaver.Save(bfMesh, Context.Mesh, dstFolder + "/" + nameMesh + ".doub");

                    for (int j = 0; j < smrs[i].sharedMaterials.Length; j++)
                    {
                        ByteBuffer bfMaterial = MaterialSaver.Save(smrs[i].sharedMaterials[j]);
                        FileSaver.Save(bfMaterial, Context.Material, dstFolder + "/" + smrs[i].sharedMaterials[j].name + ".doub");
                    }
                }
            }
            else
            {
                UnityEngine.Debug.LogError("资源装载失败:" + src);
            }
        }
Пример #6
0
        /**
         * Load the saved room.
         */
        public void LoadRoom()
        {
            if (SpatialMappingManager.IsInitialized && WorldAnchorManager.IsInitialized)
            {
                // Attach world anchor
                WorldAnchorManager.Instance.AttachAnchor(this.gameObject, this.fileName);

                // Set this cached room as the new spatial mapping source
                SpatialMappingManager.Instance.SetSpatialMappingSource(this);

                // Cleanup
                this.Cleanup();

                // Try loading the file
                try {
                    IList <Mesh> storedMeshes = MeshSaver.Load(this.fileName);
                    for (int iMesh = 0; iMesh < storedMeshes.Count; iMesh++)
                    {
                        SurfaceObject surface = this.CreateSurfaceObject(storedMeshes[iMesh], "storedmesh-" + iMesh, this.transform, iMesh);
                        this.AddSurfaceObject(surface);
                    }
                } catch {
                    this.logger.Log("Failed to load " + this.fileName + ".");
                }
            }
        }
Пример #7
0
    public bool Load()
    {
        bool errored = RoomId == null;

        if (!errored)
        {
            try
            {
                var meshes = MeshSaver.Load(RoomId);

                for (int iMesh = 0; iMesh < meshes.Count; iMesh++)
                {
                    var obj = new GameObject("mesh-" + iMesh);
                    obj.transform.SetParent(gameObject.transform);
                    obj.layer = SpatialMappingManager.Instance.PhysicsLayer;

                    var meshFilter = obj.AddComponent <MeshFilter>();
                    meshFilter.sharedMesh = meshes[iMesh];

                    var renderer = obj.AddComponent <MeshRenderer>();
                    renderer.sharedMaterial = RenderMaterial;
                    renderer.enabled        = DrawMesh;

                    var collider = obj.AddComponent <MeshCollider>();
                    collider.sharedMesh = meshes[iMesh];
                }
            }
            catch (System.Exception)
            {
                errored = true;
            }
        }

        return(!errored);
    }
Пример #8
0
        /// <summary>
        /// 保存模型
        /// </summary>
        /// <returns></returns>
        public JsonResult Add()
        {
            var saver  = new MeshSaver();
            var result = saver.Save(HttpContext.Current);

            return(Json(result));
        }
Пример #9
0
    public void LoadMesh()
    {
        if (!string.IsNullOrEmpty(FilePath) &&
            File.Exists(FilePath))
        {
//			Debug.Log (FilePath);
            Mesh[] childMeshes = MeshSaver.LoadMesh(FilePath);

            ParentRoom      = new GameObject();
            ParentRoom.name = "ParentRoom";

            for (int i = 0; i < childMeshes.Length; i++)
            {
                GameObject child = new GameObject();
                var        mf    = child.AddComponent <MeshFilter>();
                mf.mesh = childMeshes[i];
                var mr = child.AddComponent <MeshRenderer>();
                mr.material = new Material(Shader.Find("Standard"));
                mr.material.SetColor("_Color", loadedMeshColor);

                // Set name appropraitely
                child.name = childMeshes[i].name;

                // Set transform parent to be the empty gameobject generated
                child.transform.SetParent(ParentRoom.transform);
                child.SetActive(false);
            }
        }
        else
        {
            Debug.Log("Enter valid File path");
        }
    }
Пример #10
0
    public void LoadMesh()
    {
        if (!string.IsNullOrEmpty(FilePath) &&
            File.Exists(FilePath))
        {
            Mesh[] childMeshes = MeshSaver.LoadMesh(FilePath);

            GameObject go = new GameObject();
            go.name = childMeshes[0].name;

            for (int i = 0; i < childMeshes.Length; i++)
            {
                GameObject child = new GameObject();
                var        mf    = child.AddComponent <MeshFilter>();
                mf.mesh = childMeshes[i];
                var mr = child.AddComponent <MeshRenderer>();
                mr.material = new Material(Shader.Find("Standard"));
                mr.material.SetColor("_Color", loadedMeshColor);

                // Set name appropraitely
                child.name = childMeshes[i].name;

                // Set transform parent to be the empty gameobject generated
                child.transform.SetParent(go.transform);
            }
        }
    }
Пример #11
0
 public void SaveMesh()
 {
     if (MeshParent != null &&
         !string.IsNullOrEmpty(FilePath))
     {
         MeshSaver.SaveObjectMesh(MeshParent, FilePath);
     }
 }
Пример #12
0
    void Start()
    {
        ObjImporter newMesh    = new ObjImporter();
        Mesh        holderMesh = newMesh.ImportFile(fileLoc);

        // Mesh holderMesh  = FastObjImporter.Instance.ImportFile(fileLoc);

        MeshSaver.SaveMesh(holderMesh, meshname);
    }
Пример #13
0
        public void Init()
        {
            ab = TestData.LoadBundle("skeletontest.bundle");
            go = TestData.LoadFirstAsset <GameObject> (ab);
            Assert.IsNotNull(go);

            smr = go.GetComponentInChildren <SkinnedMeshRenderer> ();
            ByteBuffer result = MeshSaver.Save(smr.sharedMesh, smr.bones);

            mesh = Schema.Mesh.GetRootAsMesh(result);
        }
Пример #14
0
        private async void GetTextBlobCompleteAsync(RestResponse response)
        {
            if (response.IsError)
            {
                Debug.Log(response.ErrorMessage + " Error getting blob:" + response.Content);
                return;
            }
            Debug.Log("Received blob:" + response.Content.Length);
            string filename = await MeshSaver.SaveStringAsTemporaryMeshAsync(response.Content);

            Debug.Log("Mesh Saved At " + filename);
            ModelViewer.Instance.Filename = filename;
            ViewManager.Instance.InitializeVisualization();
        }
Пример #15
0
 public void LoadSpatialMeshes()
 {
     if (string.IsNullOrEmpty(storedMeshFilename))
     {
         Debug.Log("No mesh file specified.");
         return;
     }
     try
     {
         SpatialMappingManager.Instance.SetSpatialMappingSource(cachedSpatialMapping);
         cachedSpatialMapping.Load(MeshSaver.Load(storedMeshFilename));
     }
     catch
     {
         Debug.Log("Failed to load " + storedMeshFilename);
     }
 }
    void SaveMesh()
    {
        // SimpleMeshSerializer saves minimal mesh data (vertices and triangle indices) in the following format:
        // File header: vertex count (32 bit integer), triangle count (32 bit integer)
        // Vertex list: vertex.x, vertex.y, vertex.z (all 32 bit float)
        // Triangle index list: 32 bit integers

        List <MeshFilter> meshFilters = SpatialMappingManager.Instance.GetMeshFilters();

        m_CurrentMeshFilename = string.Format("{0}_mesh", m_CurrentRecordingLabel);

        Debug.Log("Saving mesh...");
        string meshFilepath = MeshSaver.Save(m_CurrentMeshFilename, meshFilters);

        m_CurrentMeshFilepath = meshFilepath;

        Debug.Log("Saved mesh");
    }
Пример #17
0
        public async Task <string> SaveRoomAsync(string metadata = "")
        {
            // if the anchor store is not ready then we cannot save the room mesh
            //if (anchorStore == null)
            //{
            //    Debug.Log("Anchor Store Issue");
            //    return null;
            //}

            //// delete old relevant anchors
            //string[] anchorIds = anchorStore.GetAllIds();
            //for (int i = 0; i < anchorIds.Length; i++)
            //{
            //    if (anchorIds[i].Contains(anchorStoreName))
            //    {
            //        anchorStore.Delete(anchorIds[i]);
            //    }
            //}

            Debug.Log("Old anchors deleted...");

            // get all mesh filters used for spatial mapping meshes
            roomMeshFilters = SpatialUnderstanding.Instance.UnderstandingCustomMesh.GetMeshFilters() as List <MeshFilter>;
            Debug.Log("Mesh filters fetched...");

            // create new list of room meshes for serialization
            List <Mesh> roomMeshes = new List <Mesh>();

            // cycle through all room mesh filters
            foreach (MeshFilter filter in roomMeshFilters)
            {
                // increase count of meshes in room
                meshCount++;

                string meshName = anchorStoreName + meshCount.ToString();
                filter.mesh.name = meshName;

                roomMeshes.Add(filter.mesh);
            }
            return(await MeshSaver.SaveAsObjAsync(fileName, roomMeshes, metadata));

            // serialize and save meshes
        }
Пример #18
0
        /// <summary>
        /// To record a first person video, as well as the room geometry
        /// For debugging
        /// [interal use]
        /// </summary>
        protected void VideoStart()
        {
            UVideoCapture.Instance.GetVideoCaptureAsync(OnVideoCreated);
            UVideoCapture.Instance.FrameSampleAcquired += OnFrameCaptured;
            Configurations.Instance.SetAndAddCallback("Utilities_Record", false, v =>
            {
                if (v)
                {
                    OutputDirectory = Utilities.TimeNow();
                    Utilities.CreateFolder(OutputDirectory);
                    VideoFrames       = File.Create(Utilities.FullPath(Path.Combine(OutputDirectory, "frames.raw")));
                    VideoBinaryWriter = new BinaryWriter(VideoFrames);
                    UVideoCapture.Instance.StartCamera();
                }
                else
                {
                    UVideoCapture.Instance.StopCamera();
                    VideoBinaryWriter.Dispose();
                    VideoFrames.Dispose();

                    MeshSaver.Save("room", SpatialMappingManager.Instance.GetMeshFilters());
                }
            }, Configurations.RunOnMainThead.YES, Configurations.WaitUntilDone.NO);
        }
Пример #19
0
    public void SaveRoom()
    {
        // if the anchor store is not ready then we cannot save the room mesh
        if (anchorStore == null)
        {
            return;
        }

        // delete old relevant anchors
        string[] anchorIds = anchorStore.GetAllIds();
        for (int i = 0; i < anchorIds.Length; i++)
        {
            if (anchorIds[i].Contains(anchorStoreName))
            {
                anchorStore.Delete(anchorIds[i]);
            }
        }

        Debug.Log("Old anchors deleted...");

        // get all mesh filters used for spatial mapping meshes
        roomMeshFilters = SpatialMappingManager.Instance.GetMeshFilters() as List <MeshFilter>;

        Debug.Log("Mesh filters fetched...");

        // create new list of room meshes for serialization
        List <Mesh> roomMeshes = new List <Mesh>();

        // cycle through all room mesh filters
        foreach (MeshFilter filter in roomMeshFilters)
        {
            // increase count of meshes in room
            meshCount++;

            // make mesh name = anchor name + mesh count
            string meshName = anchorStoreName + meshCount.ToString();
            filter.mesh.name = meshName;

            // Debug.Log("Mesh " + filter.mesh.name + ": " + filter.transform.position + "\n--- rotation " + filter.transform.localRotation + "\n--- scale: " + filter.transform.localScale);
            // add mesh to room meshes for serialization
            roomMeshes.Add(filter.mesh);

            // save world anchor
            WorldAnchor attachingAnchor = filter.gameObject.GetComponent <WorldAnchor>();
            if (attachingAnchor == null)
            {
                attachingAnchor = filter.gameObject.AddComponent <WorldAnchor>();
                // Debug.Log("" + filter.mesh.name + ": Using new anchor...");
            }
            else
            {//
                // Debug.Log("" + filter.mesh.name + ": Deleting existing anchor...");
                DestroyImmediate(attachingAnchor);
                //  Debug.Log("" + filter.mesh.name + ": Creating new anchor...");
                attachingAnchor = filter.gameObject.AddComponent <WorldAnchor>();
            }
            if (attachingAnchor.isLocated)
            {
                if (!anchorStore.Save(meshName, attachingAnchor))
                {
                    Debug.Log("" + meshName + ": Anchor save failed...");
                }
                else
                {
                    Debug.Log("" + meshName + ": Anchor SAVED...");
                }
            }
            else
            {
                attachingAnchor.OnTrackingChanged += AttachingAnchor_OnTrackingChanged;
            }
        }

        // serialize and save meshes
        MeshSaver.Save(fileName, roomMeshes);
    }
Пример #20
0
    // Update is called once per frame.
    void Update()
    {
        if (!_isStarted)
        {
            return;
        }

        // If we have a connected client, presumably the client wants to send some meshes.
        if (ClientConnected)
        {
            if (Global.clientStatus == Global.netStatus.NotConnected)
            {
                Global.clientStatus = Global.netStatus.Ready;
            }

            // Get the clients stream.
            NetworkStream stream = networkClient.GetStream();

            // Make sure there is data in the stream.
            if (stream.DataAvailable)
            {
                // The first 4 bytes will be the size of the data containing the mesh(es).
                int datasize = ReadInt(stream);

                // Allocate a buffer to hold the data.
                byte[] dataBuffer = new byte[datasize];

                // Read the data.
                // The data can come in chunks.
                int readsize = 0;

                while (readsize != datasize)
                {
                    readsize += stream.Read(dataBuffer, readsize, datasize - readsize);
                }

                if (readsize != datasize)
                {
                    Debug.Log("reading data failed: " + readsize + " != " + datasize);
                }

                //print out the size of the packet for debugging purposes
                //UnityEngine.Debug.Log("size of packet: " + dataBuffer.Length);


                // DONE READING IN THE DATA AT THIS POINT --
                // NOW DO STUFF WITH THE DATA...
                //
                //dataBuffer variable holds the data to decode from byte[]
                interpretIncomingPackage(dataBuffer, datasize);

                // Finally disconnect.
                ClientConnected = false;
                networkClient.Close();

                // And wait for the next connection asynchronously.
                AsyncCallback callback = new AsyncCallback(OnClientConnect);
                networkListener.BeginAcceptTcpClient(callback, this);
            }
        }

        if (Input.GetKeyDown("s")) // Save
        {
            MeshSaver.Save("MeshSave", globalMeshes);
        }
        else if (Input.GetKeyDown("l")) // Load
        {
            globalMeshes = (List <Mesh>)MeshSaver.Load("MeshSave");
            for (int index = 0; index < globalMeshes.Count; index++)
            {
                GameObject surface = AddSurfaceObject(globalMeshes[index], string.Format("Beamed-{0}", surfaceObjects.Count), transform);
                surface.transform.parent = SpatialMappingManager.Instance.transform;
                surface.GetComponent <MeshRenderer>().enabled           = true;
                surface.GetComponent <MeshRenderer>().shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On;
            }
        }

        // *******
        // The rest of the Update() look handles recieving data from the
        //  Non-Hololens clients. Both Hololens and Non-Hololens clients
        //  messages go through interpretIncomingPackage()
        // *******
        byte[] recBuffer = new byte[bufferSize];

        NetworkEventType recData = NetworkTransport.Receive(out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error);

        switch (recData)
        {
        case NetworkEventType.Nothing:
            break;

        case NetworkEventType.ConnectEvent:
        {
            Global.connectionIDs.Add(connectionId);
            Debug.Log(String.Format("Connection to host {0}, connection {1}", recHostId, connectionId));
            break;
        }

        case NetworkEventType.DataEvent:
        {
            // Strip out the sent message size
            int messageSize = BitConverter.ToInt32(recBuffer, 0);
            // Create an array of that size
            byte[] messageData = new byte[messageSize - 4];
            // Copy the data we have into said array
            System.Buffer.BlockCopy(recBuffer, 4, messageData, 0, dataSize - 4);

            // While we haven't recieved all data..
            int givenDataSize = dataSize;
            while (givenDataSize < messageSize)
            {
                // Recieve more, put it into the messageData array, add to our size, repeat..
                NetworkTransport.Receive(out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error);
                System.Buffer.BlockCopy(recBuffer, 0, messageData, givenDataSize, dataSize);
                givenDataSize += dataSize;
            }

            if (messageSize < givenDataSize)
            {
                Debug.LogError("Recieved more bytes than sent by client! Recieved " + givenDataSize + " bytes, expected " + messageSize + " bytes");
            }
            //Debug.Log(String.Format("Received event and Sent message: host {0}, connection {1}, message length {2}", recHostId, connectionId, messageData.Length));

            // Now, send that data along to the interpret function
            interpretIncomingPackage(messageData, messageData.Length);

            // From here, forward the message to all other clients (incl. Hololens)?
            Global.AddForwardMessage(messageData, connectionId);
        }
        break;

        case NetworkEventType.DisconnectEvent:
        {
            Debug.Log(String.Format("Disconnect from host {0}, connection {1}", recHostId, connectionId));
            Global.connectionIDs.Remove(connectionId);

            // Delete the Vive avatar for whichever Vive machine is currently disconnecting
            for (int i = 0; i < ViveMachines.Count; i++)
            {
                if (ViveMachines[i].connectionID == connectionId)
                {
                    Global.DeleteObject(ViveMachines[i].headsetID);
                    Global.DeleteObject(ViveMachines[i].leftControllerID);
                    Global.DeleteObject(ViveMachines[i].rightControllerID);
                    ViveMachines.RemoveAt(i);
                    break;
                }
            }

            break;
        }
        }
    }
Пример #21
0
        private static void Export()
        {
            EditorUtility.DisplayProgressBar("Exporting", "Exporting terrain to file...", 1f);
            try
            {
                List <Mesh>         meshes      = new List <Mesh>();
                TerrainToFileConfig config      = TerrainToFileConfig.Instance;
                GStylizedTerrain    terrain     = config.Terrain;
                GTerrainData        terrainData = terrain.TerrainData;
                int gridSize = terrainData.Geometry.ChunkGridSize;
                int lod      = config.LOD;

                for (int z = 0; z < gridSize; ++z)
                {
                    for (int x = 0; x < gridSize; ++x)
                    {
                        Vector2 meshIndex = new Vector2(x, z);
                        Mesh    m         = terrainData.GeometryData.GetMesh(GTerrainChunk.GetChunkMeshName(meshIndex, lod));
                        if (m != null)
                        {
                            meshes.Add(m);
                        }
                    }
                }

                string fileName = string.Format("{0}_{1}_{2}",
                                                config.Terrain.name.Replace(" ", "_"),
                                                config.Terrain.GetInstanceID().ToString(),
                                                "LOD" + config.LOD);

                string filePath = null;
                if (config.FileType == MeshSaver.FileType.Obj)
                {
                    filePath = MeshSaver.SaveObjMultipleMesh(meshes.ToArray(), config.Directory, fileName);
                }
                else if (config.FileType == MeshSaver.FileType.Fbx)
                {
                    filePath = MeshSaver.SaveFbxMultipleMesh(meshes.ToArray(), config.Directory, fileName);
                }

                AssetDatabase.Refresh();

                if (!string.IsNullOrEmpty(filePath))
                {
                    string        assetPath = filePath;
                    ModelImporter importer  = ModelImporter.GetAtPath(assetPath) as ModelImporter;
                    if (importer != null)
                    {
                        importer.useFileScale = false;
                        importer.weldVertices = false;
                        importer.SaveAndReimport();
                    }

                    Object asset = AssetDatabase.LoadAssetAtPath <Object>(assetPath);
                    if (asset != null)
                    {
                        Selection.activeObject = asset;
                        EditorGUIUtility.PingObject(asset);
                    }
                }
            }
            catch (System.Exception e)
            {
                Debug.LogError(e);
            }

            EditorUtility.ClearProgressBar();
        }
        private static void Export()
        {
            EditorUtility.DisplayProgressBar("Exporting", "Exporting terrain to file...", 1f);
            try
            {
                List <Mesh>         meshes      = new List <Mesh>();
                TerrainToFileConfig config      = TerrainToFileConfig.Instance;
                GStylizedTerrain    terrain     = config.Terrain;
                GTerrainData        terrainData = terrain.TerrainData;
                int gridSize = terrainData.Geometry.ChunkGridSize;
                int lod      = config.LOD;

                GTerrainChunk[] chunks = terrain.GetComponentsInChildren <GTerrainChunk>();
                for (int i = 0; i < chunks.Length; ++i)
                {
                    Mesh m = chunks[i].MeshFilterComponent.sharedMesh;
                    if (m != null)
                    {
                        Mesh      cloneMesh      = Object.Instantiate(m);
                        Matrix4x4 chunkToWorld   = chunks[i].transform.localToWorldMatrix;
                        Matrix4x4 worldToTerrain = terrain.transform.worldToLocalMatrix;
                        Matrix4x4 matrix         = chunkToWorld * worldToTerrain;
                        TransformMesh(cloneMesh, matrix);
                        meshes.Add(cloneMesh);
                    }
                }

                string fileName = string.Format("{0}_{1}_{2}",
                                                config.Terrain.name.Replace(" ", "_"),
                                                config.Terrain.GetInstanceID().ToString(),
                                                "LOD" + config.LOD);

                GUtilities.EnsureDirectoryExists(config.Directory);
                string filePath = null;
                if (config.FileType == MeshSaver.FileType.Obj)
                {
                    filePath = MeshSaver.SaveObjMultipleMesh(meshes.ToArray(), config.Directory, fileName);
                }
                else if (config.FileType == MeshSaver.FileType.Fbx)
                {
                    filePath = MeshSaver.SaveFbxMultipleMesh(meshes.ToArray(), config.Directory, fileName);
                }

                for (int i = 0; i < meshes.Count; ++i)
                {
                    Object.DestroyImmediate(meshes[i]);
                }

                AssetDatabase.Refresh();

                if (!string.IsNullOrEmpty(filePath))
                {
                    string        assetPath = filePath;
                    ModelImporter importer  = ModelImporter.GetAtPath(assetPath) as ModelImporter;
                    if (importer != null)
                    {
                        importer.useFileScale = false;
                        importer.weldVertices = false;
                        importer.SaveAndReimport();
                    }

                    Object asset = AssetDatabase.LoadAssetAtPath <Object>(assetPath);
                    if (asset != null)
                    {
                        Selection.activeObject = asset;
                        EditorGUIUtility.PingObject(asset);
                    }
                }
            }
            catch (System.Exception e)
            {
                Debug.LogError(e);
            }

            EditorUtility.ClearProgressBar();
        }
Пример #23
0
        private async void Update_MeshAsync()
        {
            if (_infoUpdated)
            {
                _infoUpdated = false;
                StringBuilder builder = new StringBuilder();
                builder.AppendLine($"Floor Area         {meshInfo.HorizSurfaceArea}m\xB2");
                builder.AppendLine($"Wall Area          {meshInfo.WallSurfaceArea}m\xB2");
                builder.AppendLine($"Ceiling Area       {meshInfo.VirtualCeilingSurfaceArea}m\xB2");
                builder.AppendLine($"Total Surface Area {meshInfo.TotalSurfaceArea}m\xB2");
                Debug.Log(builder.ToString());
                meshInfoText.text = builder.ToString();
            }
            if (_filechanged)
            {
                _filechanged = false;
                DebugDialog.Instance.PrimaryText = "Generating Mesh...";
                testMeshList.Clear();
                meshInfoText.text = string.Empty;
                Component[] previous = MeshHolder.GetComponentsInChildren <MeshRenderer>();
                foreach (Component comp in previous)
                {
                    //Debug.Log("Destroying..." + comp.name);
                    Destroy(comp.gameObject);
                }
                List <string> meshStringList = SplitMesh(Filename);
                //                const string V = @"o Cube
                //v 1.000000 -1.000000 -1.000000
                //v 1.000000 -1.000000 1.000000
                //v -1.000000 -1.000000 1.000000
                //v -1.000000 -1.000000 -1.000000
                //v 1.000000 1.000000 -1.000000
                //v 0.999999 1.000000 1.000001
                //v -1.000000 1.000000 1.000000
                //v -1.000000 1.000000 -1.000000
                //vt 2.094305 1.396205
                //vt 1.396205 2.094305
                //vt 0.698100 1.396205
                //vt 1.396205 0.698100
                //vt 5.000000 5.000000
                //vt 2.792410 5.000000
                //vt 2.792410 2.792410
                //vt 5.000000 2.792410
                //vt 2.792410 2.094305
                //vt 2.094305 2.792410
                //vt 0.698100 2.792410
                //vt 0.000000 2.094305
                //vt 0.000000 0.698100
                //vt 0.698100 0.000000
                //vt 2.792410 0.698100
                //vt 2.094305 0.000000
                //f 1/1/1 2/2/2 3/3/3
                //f 1/1/1 3/3/3 4/4/4
                //f 5/5/5 8/8/6 7/7/7
                //f 5/5/5 7/7/7 6/6/8
                //f 1/1/1 5/5/9 6/6/10
                //f 1/1/1 6/6/10 2/2/2
                //f 2/2/2 6/6/11 7/7/12
                //f 2/2/2 7/7/12 3/3/3
                //f 3/3/3 7/7/13 8/8/14
                //f 3/3/3 8/8/14 4/4/4
                //f 5/5/15 1/1/1 4/4/4
                //f 5/5/15 4/4/4 8/8/16";
                //                List<string> meshStringList = new List<string>();
                //                meshStringList.Add(V) ;

                meshStringList.ForEach(i =>
                {
                    StartCoroutine(BuildSubmesh(i));
                });
                Debug.Log("Parent Generated");
                GazeStabilizer stabalizer = MeshHolder.AddComponent <GazeStabilizer>();
                DebugDialog.Instance.ClearText();
                Debug.Log("Mesh List" + testMeshList.Count);
                string t = await MeshSaver.SaveAsObjAsync("test_mesh_out", testMeshList);

                Debug.Log(t);
            }
        }
Пример #24
0
 /// <summary>
 /// Saves all the currently created spatial source meshes in world space.
 /// </summary>
 /// <param name="fileName">Name to give the mesh file. Exclude path and extension.</param>
 public void SaveSpatialMeshes(string fileName)
 {
     MeshSaver.Save(fileName, GetMeshFilters());
 }