MeshToFile() public static method

public static MeshToFile ( MeshFilter mf, string directory, string filename ) : void
mf UnityEngine.MeshFilter
directory string
filename string
return void
Exemplo n.º 1
0
    void Awake()
    {
        // save the parent GO-s pos+rot
        Vector3    position = transform.position;
        Quaternion rotation = transform.rotation;

        // move to the origin for combining
        transform.position = Vector3.zero;
        transform.rotation = Quaternion.identity;

        MeshFilter[]           filters = GetComponentsInChildren <MeshFilter>();
        List <CombineInstance> combine = new List <CombineInstance>();

        for (int i = 0; i < filters.Length; i++)
        {
            // skip the empty parent GO
            if (filters[i].sharedMesh == null)
            {
                continue;
            }

            // combine submeshes
            for (int j = 0; j < filters[i].sharedMesh.subMeshCount; j++)
            {
                CombineInstance ci = new CombineInstance();

                ci.mesh         = filters[i].sharedMesh;
                ci.subMeshIndex = j;
                ci.transform    = filters[i].transform.localToWorldMatrix;

                combine.Add(ci);
            }

            // disable child mesh GO-s
            filters[i].gameObject.SetActive(false);
        }

        MeshFilter filter = GetComponent <MeshFilter>();

        filter.mesh = new Mesh();
        filter.mesh.CombineMeshes(combine.ToArray(), true, true);

        // restore the parent GO-s pos+rot
        transform.position = position;
        transform.rotation = rotation;

        ObjExporter.MeshToFile(filter, Application.persistentDataPath + "testobj.obj");



        Mesh        holderMesh = new Mesh();
        ObjImporter newMesh    = new ObjImporter();

        holderMesh = newMesh.ImportFile(Application.persistentDataPath + "testobj.obj");

        MeshRenderer renderer = g1.GetComponent <MeshRenderer>();
        MeshFilter   filter1  = g1.GetComponent <MeshFilter>();

        filter1.mesh = holderMesh;
    }
 // Update is called once per frame
 void Update()
 {
     targetObject = GameObject.FindGameObjectWithTag("Fractal");
     if (combine)
     {
         MeshFilter[]      meshFilters = targetObject.GetComponentsInChildren <MeshFilter>();
         CombineInstance[] combines    = new CombineInstance[meshFilters.Length];
         int i = 0;
         while (i < meshFilters.Length)
         {
             combines[i].mesh      = meshFilters[i].sharedMesh;
             combines[i].transform = meshFilters[i].transform.localToWorldMatrix;
             i++;
             //meshFilters[i].gameObject.SetActive(false);
         }
         transform.GetComponent <MeshFilter>().mesh = new Mesh();
         transform.GetComponent <MeshFilter>().mesh.CombineMeshes(combines);
         transform.GetComponent <MeshRenderer>().material = (Material)Resources.Load("combined");
         combine = false;
     }
     if (saveObj)
     {
         if (transform.GetComponent <MeshFilter>().mesh != null)
         {
             ObjExporter.MeshToFile(transform.GetComponent <MeshFilter>(), targetObject.name + ".obj");
         }
         saveObj = false;
     }
     if (saveObjNoCombine)
     {
         ObjExporter.MeshToFile(targetObject.GetComponent <MeshFilter>(), "testsetset.obj");
         saveObjNoCombine = false;
     }
 }
Exemplo n.º 3
0
    // Use this for initialization
    void Start()
    {
        percent    = .25f;
        _mRenderer = GetComponent <MeshRenderer> ();
        mf         = GetComponent <MeshFilter> ();

        if (_createMesh)
        {
            br.RegenerateMesh();
            meshFromBorder = br.CloneBorderMesh;
            mf.mesh        = meshFromBorder;
            ObjExporter.MeshToFile(mf, "MyTallerMesh.obj");
            Debug.Log("Created a mesh Object in root directory");

            var savePath = "Assets/" + "BorderMesh" + ".asset";
            Debug.Log("Saved Mesh to:" + savePath);
#if UNITY_EDITOR
            AssetDatabase.CreateAsset(mf.mesh, savePath);                         //This to be commented out when building
                        #endif
        }
        else
        {
            mf.mesh = _meshes [(int)meshSize];
        }



        _mRenderer.material.color = _firstColor;
        //	_thirdColor = _firstColor;
    }
Exemplo n.º 4
0
        void WriteModelFiles(ThreeSceneRoot root, SceneFormat fmt)
        {
            // three.js는 단일 파일로 출력하는게 목적이라서 model 파일을 생성하지 않는다
            var pathHelper = ExportPathHelper.Instance;

            if (fmt == SceneFormat.AFrame)
            {
                foreach (var el in root.SharedNodeTable.GetEnumerable <MeshElem>())
                {
                    var bufferGeom = el.Geometry as BufferGeometryElem;
                    if (bufferGeom != null)
                    {
                        string filepath = pathHelper.ToModelPath(bufferGeom.CreateMeshFileName(".obj"));
                        ObjExporter.MeshToFile(bufferGeom.Mesh, filepath);
                    }

                    var mtl = MaterialFacade.Instance.CreateMaterial(el.Material);
                    if (bufferGeom != null)
                    {
                        string filepath = pathHelper.ToModelPath(bufferGeom.CreateMeshFileName(".mtl"));
                        MtlExporter.ToFile(mtl, bufferGeom.SafeName, filepath);
                    }
                }
            }
        }
Exemplo n.º 5
0
    public void Export()
    {
        if (m_bIsExportMesh)
        {
            if (m_strMeshName == null)
            {
                m_strMeshName = "meshedit_exportmesh";
            }
            else if (m_strMeshName.Length == 0)
            {
                m_strMeshName = "meshedit_exportmesh";
            }

            m_meshOutput.name = m_strMeshName;

//			if (m_strMeshPath == null)
//			{
            Mesh mesh = GetComponent <MeshFilter>().sharedMesh;
            GetComponent <MeshFilter> ().mesh = m_meshOutput;
            ObjExporter.MeshToFile(GetComponent <MeshFilter>(), m_strMeshName);
            GetComponent <MeshFilter>().mesh = mesh;
            Debug.Log(name + ".Meshedit.Export(): Exported mesh to Assets", this.gameObject);
//			}
//			else if (m_strMeshPath.Length == 0)
//				UnityEditor.AssetDatabase.CreateAsset (m_meshOutput, "Assets/" + m_strMeshPath  + "/" + m_strMeshName + ".obj");
        }
    }
Exemplo n.º 6
0
    public override void OnPress()
    {
        // re-initialize export number so user can re-export solids if they wish to
        exportNumber = initialExportNumber;

        foreach (Solid solid in DCGBase.solids)
        {
            string filePath = "Assets/Resources/Exports/Meshes/";
            string fileName = "export" + exportNumber;
            filePath += fileName + ".obj";

            /* create empty game object, add mesh filter and mesh renderer to it
             * initialize mesh filter with meshs from dcgbase >> solids */
            GameObject go         = new GameObject();
            MeshFilter meshFilter = go.AddComponent <MeshFilter>();
            meshFilter.sharedMesh = solid.getMesh();
            MeshRenderer meshRenderer = go.AddComponent <MeshRenderer>();
            meshRenderer.material = exportMaterial;
            Debug.Log("Exporting solid to " + filePath);
            ObjExporter.MeshToFile(meshFilter, filePath);

            exportNumber++;
        }
        StartCoroutine(displayExportedText());
        base.OnPress();
    }
Exemplo n.º 7
0
    public override void OnInspectorGUI()
    {
        myTargets = targets;

        string filePath = EditorGUILayout.TextField("file path:", (Application.dataPath + "/RoadEditor/Exports/"));


        string multiText = "";

        if (myTargets.Length > 1)
        {
            multiText += "(multiSelected)";
        }
        worldMatrix          = GUILayout.Toggle(worldMatrix, "Use World Space Positions");
        correctedXAxisExport = GUILayout.Toggle(correctedXAxisExport, "export with inverted x-axis ");
        // export
        if (GUILayout.Button("Export OBJ" + multiText))
        {
            for (int i = 0; i < myTargets.Length; i++)
            {
                tempTrack = (Track)myTargets[i];
                MeshFilter combineMeshFilter = tempTrack.getCombimedMeshFilter();
                ObjExporter.MeshToFile(combineMeshFilter, filePath, (tempTrack.getName + ".obj"), correctedXAxisExport, worldMatrix);
                DestroyImmediate(combineMeshFilter.gameObject);
            }
        }

        EditorApplication.update += (EditorApplication.CallbackFunction)EditortUpdate;

        DrawDefaultInspector();
    }
Exemplo n.º 8
0
 // Update is called once per frame
 void Update()
 {
     if (save)
     {
         ObjExporter.MeshToFile(targetObject, targetObject.name + ".obj");
         save = false;
     }
 }
Exemplo n.º 9
0
 public override void OnInspectorGUI()
 {
     base.OnInspectorGUI();
     if (GUILayout.Button("Button"))
     {
         RotModel obj = (RotModel)target;
         ObjExporter.MeshToFile(obj.Gc <MeshFilter>(), "Assets/" + obj.name + ".obj");
     }
 }
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        if (GUILayout.Button("Dump Mesh"))
        {
            MeshFilter mf = (MeshFilter)target;
            ObjExporter.MeshToFile(mf, Application.dataPath + "/" + mf.name + "-" + mf.mesh.name + ".obj");
        }
    }
Exemplo n.º 11
0
    // Update is called once per frame
    void Update()
    {
        if (once)
        {
            once = false;

            ObjExporter.MeshToFile(meshFilter, "Assets/" + nameMesh + ".obj");
            print("Mesh successfully exported : " + nameMesh + ".obj");
        }
    }
Exemplo n.º 12
0
    void createOBJ()
    {
        if (objMade == false)
        {
            objMade = true;

            _vertBuffer.GetData(inValues);

            print(inValues[0]);

            int numVertsTotal = ribbonWidth * 3 * 2 * (ribbonLength);


            AssignStructs.MeshInfo mesh = new AssignStructs.MeshInfo();

            Vector3[] verts     = new Vector3[ribbonLength * ribbonWidth];
            Vector3[] norms     = new Vector3[ribbonLength * ribbonWidth];
            Vector2[] uvs       = new Vector2[ribbonLength * ribbonWidth];
            int[]     triangles = new int[numVertsTotal];

            for (int i = 0; i < ribbonWidth * ribbonLength; i++)
            {
                int baseID = i * AssignStructs.VertC4StructSize;

                Vector3 v = new Vector3(inValues[baseID + 0], inValues[baseID + 1], inValues[baseID + 2]);
                Vector3 n = new Vector3(inValues[baseID + 6], inValues[baseID + 7], inValues[baseID + 8]);
                Vector2 u = new Vector2(inValues[baseID + 9], inValues[baseID + 10]);

                verts[i] = v;
                norms[i] = n;
                uvs[i]   = u;
            }

            for (int i = 0; i < numVertsTotal; i++)
            {
                triangles[i] = getID(i);
            }

            mesh.vertices  = verts;
            mesh.normals   = norms;
            mesh.uvs       = uvs;
            mesh.triangles = triangles;
            mesh.name      = "DONTUTEST";



            //string objString = makeString( mesh , transform );
            //print( objString );
            //WriteToFile( objString , "DONUT_TEST.obj");

            ObjExporter.MeshToFile(mesh);
        }
    }
Exemplo n.º 13
0
    void ExportMesh(GameObject obj)
    {
        if (fileFormatSelector.value == 0)
        {
            FBXExporter.ExportGameObjToFBX(obj, _path, false, false);
        }

        if (fileFormatSelector.value == 1)
        {
            ObjExporter.MeshToFile(obj.GetComponent <MeshFilter>(), _path);
        }
        Debug.Log("exported");
    }
Exemplo n.º 14
0
    public override void OnInspectorGUI()
    {
        ObjExporter script = (ObjExporter)target;

        DrawDefaultInspector();

        GUILayout.Space(20);

        if (GUILayout.Button("Build OBJ file"))
        {
            script.MeshToFile();
        }
    }
Exemplo n.º 15
0
    // Update is called once per frame
    void Update()
    {
        if (save)
        {
            save = false;
            ObjExporter.MeshToFile(GetComponent <MeshFilter>(), "meshyoyo.obj");
        }

        UpdateMiddle();
        UpdateCollider();

        UpdateDarts();
    }
Exemplo n.º 16
0
    void combiner(GameObject go, Boolean save, int clr, int filenumber)
    {
        // save the parent GO-s pos+rot
        //Vector3 position = go.transform.position;
        //Quaternion rotation = go.transform.rotation;

        // move to the origin for combining
        //transform.position = Vector3.zero;
        //transform.rotation = Quaternion.identity;

        MeshFilter[]           filters = go.GetComponentsInChildren <MeshFilter>();
        List <CombineInstance> combine = new List <CombineInstance>();

        for (int i = 0; i < filters.Length; i++)
        {
            // skip the empty parent GO
            if (filters[i].sharedMesh == null)
            {
                continue;
            }

            // combine submeshes
            for (int j = 0; j < filters[i].sharedMesh.subMeshCount; j++)
            {
                CombineInstance ci = new CombineInstance();

                ci.mesh         = filters[i].sharedMesh;
                ci.subMeshIndex = j;
                ci.transform    = filters[i].transform.localToWorldMatrix;

                combine.Add(ci);
            }

            // disable child mesh GO-s
            filters[i].gameObject.SetActive(false);
        }

        MeshFilter filter = go.GetComponent <MeshFilter>();

        filter.mesh = new Mesh();
        filter.mesh.CombineMeshes(combine.ToArray(), true, true);

        // restore the parent GO-s pos+rot
        //go.transform.position = position;
        //go.transform.rotation = rotation;

        if (save)
        {
            ObjExporter.MeshToFile(filter, Application.persistentDataPath + "testobject" + clr.ToString() + filenumber.ToString() + ".obj");
        }
    }
Exemplo n.º 17
0
    void CutMesh(Mesh cutMesh, GameObject cutMeshGO, string name)
    {
        string       cutMeshOff = ObjectFileFormat.MeshToOff(cutMesh, cutMeshGO.transform);
        StreamWriter strw       = new StreamWriter("./Assets/Models/" + cutMeshGO.name + ".off");

        strw.Write(cutMeshOff);
        strw.Close();

        string        cuttedMeshOff = System.IO.File.ReadAllText("./Assets/Models/squirrel.off");
        StringBuilder strB          = new StringBuilder();
        //Extract transformation matrix

        Matrix4x4 transformationMatrix = cuttedMeshTransform.localToWorldMatrix;

        strB.Append(transformationMatrix.m00).AppendLine();
        strB.Append(transformationMatrix.m01).AppendLine();
        strB.Append(transformationMatrix.m02).AppendLine();
        strB.Append(transformationMatrix.m03).AppendLine();
        strB.Append(transformationMatrix.m10).AppendLine();
        strB.Append(transformationMatrix.m11).AppendLine();
        strB.Append(transformationMatrix.m12).AppendLine();
        strB.Append(transformationMatrix.m13).AppendLine();
        strB.Append(transformationMatrix.m20).AppendLine();
        strB.Append(transformationMatrix.m21).AppendLine();
        strB.Append(transformationMatrix.m22).AppendLine();
        strB.Append(transformationMatrix.m23).AppendLine();

        strw = new StreamWriter("./Assets/models/matrix.txt");
        strw.Write(strB.ToString());
        strw.Close();

        IntPtr cuttedMeshPtr          = Marshal.StringToHGlobalAnsi(cuttedMeshOff);
        IntPtr cuttedMeshTransformPtr = Marshal.StringToHGlobalAnsi(strB.ToString());
        IntPtr cutMeshPtr             = Marshal.StringToHGlobalAnsi(cutMeshOff);

        IntPtr ptrResult = CGALController.booleanOperationClean(cuttedMeshPtr, cuttedMeshTransformPtr, cutMeshPtr, Marshal.StringToHGlobalAnsi("difference"));
        //Convert IntPtr to string
        string result = Marshal.PtrToStringAnsi(ptrResult);

        //exportOff (result, "mesh" + Time.fixedDeltaTime);
        // Open string stream on the result off string
        byte[]       byteArray = Encoding.UTF8.GetBytes(result);
        MemoryStream stream    = new MemoryStream(byteArray);
        //Convert off string to Mesh and add it to scene
        Mesh myMesh = ObjectFileFormat.OffToMesh(new StreamReader(stream));

        stream.Close();
        myMesh.RecalculateNormals();
        ObjExporter.MeshToFile(myMesh, name, "BenchMat");
        addMeshToSceneAndExport(name, myMesh, transform.GetComponent <Transform> ().localScale.x);
    }
Exemplo n.º 18
0
 /**
  *	\brief Exports an OBJ file to the supplied path.
  *	Files sharing a path name will not be ovewritten.
  *	\returns The path to the generated OBJ file.
  *	@param path The file path to save the resulting OBJ to.
  *	@param mf The MeshFilter to convert to an OBJ.
  */
 public string ExportOBJ(string path, MeshFilter mf)
 {
     if (File.Exists(path))
     {
         int i = 0;
         while (File.Exists(path))
         {
             path = path.Replace(".obj", "");
             path = path + i + ".obj";
             i++;
         }
     }
     ObjExporter.MeshToFile(mf, path);
     return(path);
 }
Exemplo n.º 19
0
    public void exportObject(GameObject parentObject)
    {
        parentObject.transform.position   = new Vector3(0, 0.5f, 0);
        parentObject.transform.localScale = new Vector3(100, 100, 100);
        Transform[] allChildren = GameObject.Find("ObjFactory").GetComponentsInChildren <Transform>();
        foreach (Transform child in GameObject.Find("ObjFactory").transform)
        {
            if (child.gameObject.activeSelf == true)
            {
                meshObjectList.Add(child.gameObject);
            }
        }

        //meshObjectList.Add(GO1);
        //meshObjectList.Add(Go2);
        // combine meshes
        CombineInstance[] combine = new CombineInstance[meshObjectList.Count];
        int i = 0;

        while (i < meshObjectList.Count)
        {
            MeshFilter meshFilter1 = meshObjectList[i].gameObject.GetComponent <MeshFilter>();
            combine[i].mesh      = meshFilter1.sharedMesh;
            combine[i].transform = meshFilter1.transform.localToWorldMatrix;
            i++;
        }

        Mesh combinedMesh = new Mesh();

        combinedMesh.CombineMeshes(combine);

        //Mesh mesh = CombineMeshes(new List<Mesh> { GO1.GetComponent<MeshFilter>().mesh, Go2.GetComponent<MeshFilter>().mesh });
        //Debug.Log(mesh.ToString());
        parentObject.AddComponent <MeshFilter>().mesh = combinedMesh;
        string     path       = Application.persistentDataPath + "/exporrted.OBJ";
        MeshFilter meshFilter = parentObject.GetComponent <MeshFilter>();

        Debug.Log(meshFilter.name);
        ObjExporter.MeshToFile(meshFilter, path);
        ImportFile importFile = new ImportFile();

        importFile._FileData.filePath = path;
        importFile._FileData.fileName = Path.GetFileName(path);
        importFile.SaveIntoJson();

        SceneManager.LoadScene("PlaceIt");
    }
Exemplo n.º 20
0
    void Export()
    {
        string sceneName = System.IO.Path.GetFileNameWithoutExtension(EditorApplication.currentScene);

        foreach (var mesh in generatedObject.transform.GetComponentsInChildren <MeshFilter>())
        {
            string exportPath = "Assets/" + sceneName + "/" + name + "/" + mesh.name + ".obj";
            System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(exportPath));
            ObjExporter.MeshToFile(mesh, exportPath);

            AssetDatabase.ImportAsset(exportPath);

            var importer = (ModelImporter)ModelImporter.GetAtPath(exportPath);

            importer.animationType = ModelImporterAnimationType.None;
        }
    }
    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.B))
        {
            Mesh mesh = new Mesh();

            mesh.SetVertices(Verts);
            mesh.SetUVs(0, UV);
            mesh.SetNormals(Normals);
            mesh.SetTriangles(Tris, 0);

            meshFilter.mesh = mesh;
        }
        else if (Input.GetKeyDown(KeyCode.S))
        {
            ObjExporter.MeshToFile(meshFilter, "Assets/" + FileName);
        }
    }
Exemplo n.º 22
0
        private Mesh CutMesh(Mesh cutMesh, GameObject cutMeshGO, string cuttedGoName, string cuttedMeshOff, string cuttedMeshMatrix)
        {
            /* ********** handle cut mesh ********** */
            string cutMeshOff          = ObjectFileFormat.MeshToOff(cutMesh, cutMeshGO.transform);
            IntPtr cutMeshPtr          = Marshal.StringToHGlobalAnsi(cutMeshOff);
            IntPtr cutMeshTransformPtr = Marshal.StringToHGlobalAnsi(GeomUtils.GetTransformationMatrix(cutMeshGO.transform, 0f, 0f, 0f));

            //exportOff
            //ExportOff(cutMeshOff, "./Assets/" + cutMeshGO.name + ".off");

            /* ********** handle cutted mesh ********** */
            IntPtr cuttedMeshPtr          = Marshal.StringToHGlobalAnsi(cuttedMeshOff);
            IntPtr cuttedMeshTransformPtr = Marshal.StringToHGlobalAnsi(cuttedMeshMatrix);

            //exportOff
            //ExportOff(cuttedMeshOff, "./Assets/" + cuttedGoName + ".off");

            /* ********** compute cut with CGAL********** */
            IntPtr ptrResult = CGALPlugin.BooleanOperationClean(cuttedMeshPtr, cuttedMeshTransformPtr, cutMeshPtr, cutMeshTransformPtr, Marshal.StringToHGlobalAnsi("difference"));

            //Convert IntPtr to string
            string result = Marshal.PtrToStringAnsi(ptrResult);

            //exportOff
            //ExportOff(result, DataPath + initialObjectName + parts + ".off");

            // Open string stream on the result off string
            byte[]       byteArray = Encoding.UTF8.GetBytes(result);
            MemoryStream stream    = new MemoryStream(byteArray);

            //Convert off string to Mesh and add it to scene
            Mesh myMesh = ObjectFileFormat.OffToMesh(new StreamReader(stream));

            stream.Close();
            myMesh.RecalculateNormals();

            //Export obj file
            ObjExporter.MeshToFile(myMesh, "Split-" + DateTime.Now.ToString("hhmmssffff"), "BenchMat");
#if UNITY_EDITOR
            AssetDatabase.Refresh();
#endif
            return(myMesh);
        }
Exemplo n.º 23
0
    // Update is called once per frame
    void Update()
    {
        if (reset)
        {
            resetAvatar();
        }
        else
        {
            if (checkAndUpdate())
            {
                sizeAvatar();
            }
        }
        if (Input.GetKeyDown(KeyCode.Space) && !IsInvoking("updateFromFile"))
        {
            //InvokeRepeating ("updateFromFile", 5, 30);
            Invoke("updateFromFile", 5);
        }
        if (SaveObj)
        {
            MeshFilter thisMesh = GetComponent <MeshFilter> () as MeshFilter;
            ObjExporter.MeshToFile(thisMesh, "Human2.obj");
            SaveObj = false;
        }
//        if (tmpBody != null) {
//
//            if (tmpBody.vertexIndexsPerBone.ContainsKey (boneType)) {
//                MeshFilter thisMesh = GetComponent<MeshFilter> () as MeshFilter;
//                if (thisMesh == null) {
//                    Debug.LogError ("No mesh filter");
//                    return;
//                }
//                Color[] colors = thisMesh.mesh.colors;
//                ArrayList indexList = tmpBody.vertexIndexsPerBone [boneType];
//                for (int i = 0; i < indexList.Count; ++i) {
//                    colors [(int)indexList [i]] =
//                        Color.Lerp (Color.red, Color.green, 10);//vertices[i].y);
//                }
//                thisMesh.mesh.colors = colors;
//            }
//        }
    }
Exemplo n.º 24
0
    static void ExportNavMeshToObj()
    {
        var navMeshInfo = UnityEngine.AI.NavMesh.CalculateTriangulation();

        Mesh mesh = new Mesh();

        mesh.vertices  = navMeshInfo.vertices;
        mesh.triangles = navMeshInfo.indices;
        mesh.RecalculateNormals();
        mesh.RecalculateBounds();


        GameObject navMeshFilter = new GameObject("navMeshFilter");
        MeshFilter meshFilter    = (navMeshFilter.AddComponent <MeshFilter>() as MeshFilter);

        meshFilter.sharedMesh = mesh;


        MeshRenderer meshRenderer = navMeshFilter.AddComponent <MeshRenderer>();
        Material     material     = new Material(Shader.Find("Unlit/Transparent"));

        meshRenderer.sharedMaterial = material;

        string sceneId    = EditorSceneManager.GetActiveScene().path;
        int    beignIndex = sceneId.LastIndexOf("/");
        int    endIndex   = sceneId.LastIndexOf(".");

        if (beignIndex == -1 || endIndex == -1)
        {
            return;
        }

        sceneId = sceneId.Substring(beignIndex + 1, endIndex - beignIndex - 1);

        String exportPath = EditorUtility.SaveFilePanel("Save Navmesh", "", sceneId, "obj");

        if (exportPath.Length > 0)
        {
            ObjExporter.MeshToFile(meshFilter, exportPath);
        }
    }
Exemplo n.º 25
0
        void WriteModelFiles(ThreeSceneRoot root, SceneFormat fmt)
        {
            // three.js는 단일 파일로 출력하는게 목적이라서 model 파일을 생성하지 않는다
            var pathHelper = ExportPathHelper.Instance;

            if (fmt == SceneFormat.AFrame)
            {
                foreach (var el in root.SharedNodeTable.GetEnumerable <AbstractGeometryElem>())
                {
                    // TODO 타입에 따라서 obj 굽는게 바뀔텐데
                    var bufferGeom = el as BufferGeometryElem;
                    if (bufferGeom == null)
                    {
                        continue;
                    }

                    string filepath = pathHelper.ToModelPath(bufferGeom.CreateMeshFileName(".obj"));
                    ObjExporter.MeshToFile(bufferGeom.Mesh, filepath);
                }
            }
        }
Exemplo n.º 26
0
 /**
  *	\brief Exports all selected Transform meshes to an OBJ file in the supplied path.
  *	Files sharing a path name will not be ovewritten.
  *	\returns The path to the generated OBJ(s) file.
  *	@param path The file path to save the resulting OBJ to.
  *	@param t_arr An array of Transforms to be parsed.  Typical use case for this would be in editor, calling Selection.transforms.
  */
 public static string ExportOBJ(string path, Transform[] t_arr)
 {
     foreach (Transform t in t_arr)
     {
         if (File.Exists(path))
         {
             int i = 0;
             while (File.Exists(path))
             {
                 path = path.Replace(".obj", "");
                 path = path + i + ".obj";
                 i++;
             }
         }
         if (t.GetComponent <MeshFilter>())
         {
             ObjExporter.MeshToFile(t.GetComponent <MeshFilter>(), path);
         }
     }
     return(path);
 }
Exemplo n.º 27
0
    public void saveToFile()
    {
        MeshFilter filter = GetComponent <MeshFilter>();

        if (filter)
        {
            string filename = "terrain " + DateTime.UtcNow.ToString() + ".obj";
            //	Replace '/', ':' and ' ' with '_'
            filename = filename.Replace(' ', '_');
            filename = filename.Replace('/', '_');
            filename = filename.Replace(':', '_');

            Debug.Log(filename);

            ObjExporter.MeshToFile(filter, filename);
        }
        else
        {
            Debug.Log("No MeshFilter attached.");
        }
    }
Exemplo n.º 28
0
    // Use this for initialization
    IEnumerator Start()
    {
        Loom.Current.GetComponent<Loom>();
        layerMask = 1 << 8;
        wayList = new List<long>();
        //StartCoroutine(LoadChunk(-8.6f,41.1767f,-8.55f,41.1923f));
        MapChunkLoader.precision = GeoUTMConverter.Precision;
        GeoUTMConverter latlon2Utm = new GeoUTMConverter();
        latlon2Utm.ToUTM((minimumLat+maximumLat)/2f,(minimumLon+maximumLon)/2f);

        transform.position = new Vector3(((float)latlon2Utm.X - offsetPositionX), -0.1f, ((float)latlon2Utm.Y - offsetPositionZ));

        GameObject floor = new GameObject();
        floor.name = "Ground";
        floor.isStatic = true;

        CreateGround cg = new CreateGround();
        cg.maxLat = maximumLat + 0.01f * (maximumLat - minimumLat); //0.0001f;
        cg.maxLon = maximumLon + 0.01f * (maximumLat - minimumLat);
        cg.minLat = minimumLat - 0.01f * (maximumLat - minimumLat);
        cg.minLon = minimumLon - 0.01f * (maximumLat - minimumLat);
        cg.numberOfDivisions = numberOfDivisions;

        MeshFilter mf = floor.AddComponent<MeshFilter>();

        MeshRenderer mr = floor.AddComponent<MeshRenderer>();
        mr.material = groundMaterial;
        floor.transform.position = transform.position;
        floor.transform.parent = transform;
        floor.layer = LayerMask.NameToLayer("RayCast");

        string floorPath = Application.persistentDataPath + "Assets/Resources/Objs/" + cg.maxLat + "I" + cg.maxLon + ".obj";

        if (!File.Exists(floorPath)) // If the file isn't cached we calculate everything and then we cache it
        {
            mf.sharedMesh = cg.GetGroundMesh();
            if (exportObjs)
            {
                ObjExporter oe = new ObjExporter();
                oe.MeshToFile(mf, floorPath);
            }
        }
        else
        {
            ObjImporter oi = new ObjImporter();
            StartCoroutine(oi.FileToMesh("file://" + floorPath));

            while (oi._myMesh == null)
            {
                yield return null;
            }

            mf.sharedMesh = oi._myMesh;
            Debug.LogWarning("Loaded Ground Chunk from cache");
        }

        //Texture2D t = new Texture2D(1024, 1024);

        MapTexture mt = new MapTexture();
        mt.getTexture(cg.minLon.ToString(), cg.minLat.ToString(), cg.maxLon.ToString(), cg.maxLat.ToString(),Application.persistentDataPath,mr.material);
        while (mt.texture == null)
        {
            yield return null;
        }

        //t.LoadImage(mt.ReadFully(mt.mq_dataStream));
        //mr.material.SetTexture("_MainTex", t);

        MeshCollider m = floor.AddComponent<MeshCollider>();
        Loom l = Loom.Current;
        LoadChunk(minimumLon, minimumLat, maximumLon, maximumLat);

        //StartCoroutine();
    }
Exemplo n.º 29
0
    // Update is called once per frame
    void Update()
    {
        //ROTATION
        //rotate entire mesh (including free vertices) when L index trigger is pushed
        if (OVRInput.Get(OVRInput.RawButton.LIndexTrigger))
        {
            //Archived
            //Quaternion offset = Quaternion.Inverse(controllerOrientation) * OVRInput.GetLocalControllerRotation(OVRInput.Controller.LTouch);
            // controllerOrientation = OVRInput.GetLocalControllerRotation(OVRInput.Controller.LTouch);
            //meshSpace.transform.rotation = meshSpace.transform.rotation * offset;

            meshSpace.transform.SetParent(this.transform, true);
        }

        //OPEN MENU if thumbstick is moved
        if (OVRInput.Get(OVRInput.RawAxis2D.LThumbstick) != Vector2.zero)
        {
            if (!pieMenu.isOpen())
            {
                pieMenu.Open();
            }

            pieMenu.CustomInputVector = OVRInput.Get(OVRInput.RawAxis2D.LThumbstick);
        }
        else
        //SELECT and CLOSE MENU when thumbstick is released
        {
            if (pieMenu.isOpen())
            {
                //select menu item by pressing thumbstick
                pieMenu.confirmSelect();
                pieMenu.Close();
            }
        }



        //Export mesh when X is pushed
        if (OVRInput.GetDown(OVRInput.RawButton.X))
        {
            string     savePath = "C:/Users/Davide/Desktop/export.obj";
            MeshFilter mf       = targetMeshObj.GetComponent <MeshFilter>();

            //add UVs
            Vector2[] uvs = UvCalculator.CalculateUVs(mf.mesh.vertices, 1.0f);

            mf.mesh.uv = uvs;

            ObjExporter.MeshToFile(mf, savePath);
        }


        //Import mesh when Y is pushed
        //This should only be called at the beginning of the game (no custom mesh created) for now
        if (OVRInput.GetDown(OVRInput.RawButton.Y))
        {
            string      loadPath = "C:/Users/Davide/Desktop/export.obj";
            Mesh        m        = new Mesh();
            ObjImporter importer = new ObjImporter();
            m = importer.ImportFile(loadPath);

            //DEBUG
            //print("\nLENGTH 1");
            //print((m.vertices.Length).ToString());
            //print((m.triangles.Length).ToString());

            //a hack to correct the doubling of triangles caused by import script
            int[] correctTriangles = new int[m.vertices.Length];
            for (int i = 0; i < m.vertices.Length; i++)
            {
                correctTriangles[i] = i;
            }
            m.triangles = correctTriangles;

            Material mat = new Material(Shader.Find("Custom/VertexColored"));
            if (targetMeshObj.GetComponent <MeshRenderer>() == null)
            {
                targetMeshObj.AddComponent <MeshRenderer>();
            }
            targetMeshObj.GetComponent <MeshFilter>().mesh       = m;
            targetMeshObj.GetComponent <MeshRenderer>().material = mat;

            //scale
            //targetMeshObj.transform.localScale = new Vector3(0.005f, 0.005f, 0.005f);
            //targetMeshObj.transform.Translate(0, 0, 2f);

            //DEBUG
            //print("\nLENGTH 2");
            //print((m.vertices.Length).ToString());
            //print((m.triangles.Length).ToString());

            //create vertices and related behind-the-scenes data for editing
            rightHandAnchor.GetComponent <MeshHandler>().PrepareImportedMesh();
        }
    }
Exemplo n.º 30
0
    public override IEnumerator Build(Way w, MapChunkLoader mcl)
    {
        //CreateBuilding(Way w)

        Mesh roofm = new Mesh();
        Mesh wallsm = new Mesh();

        GameObject build = new GameObject();
        build.name = "Building - " +  w.id.ToString();

        build.transform.parent = mcl.transform;
        GameObject roof = new GameObject();
        //roof.transform.position = new Vector3(0,baseHeight,0);
        roof.name = "Roof - " +(2 * w.id).ToString();
        mcl.mapManager.mapHash.Add(2 * w.id);
        mcl.wayList.Add(2 * w.id);

        GameObject walls = new GameObject();
        walls.name = "Walls - " + (3 * w.id).ToString();
        //walls.transform.position = new Vector3(0,baseHeight,0);
        mcl.mapManager.mapHash.Add(3 * w.id);
        mcl.wayList.Add(3 * w.id);

        walls.AddComponent<MeshCollider>();
        walls.AddComponent(typeof(MeshRenderer));
        MeshFilter filter = walls.AddComponent(typeof(MeshFilter)) as MeshFilter;

        roof.AddComponent<MeshCollider>();
        roof.AddComponent(typeof(MeshRenderer));
        MeshFilter filter2 = roof.AddComponent(typeof(MeshFilter)) as MeshFilter;

        string buildPath = Application.persistentDataPath + "Assets/Resources/Objs/" + build.name + ".obj";

        string roofPath = Application.persistentDataPath+"Assets/Resources/Objs/" + roof.name + ".obj";

        if (!File.Exists(buildPath) && !File.Exists(roofPath)) // If the file isn't cached we calculate everything and then we cache it
        {
            Vector3[] nodes = new Vector3[w.nodes.Count];
            Vector2[] xz = new Vector2[w.nodes.Count];

            float height = (float)w.nodes[0].northing % referenceVariationHeight + referenceBaseHeight;

            if (w.height != 0)
            {
                height = w.height;
                referenceVariationHeight = Mathf.Abs(referenceVariationHeight - height);
                referenceBaseHeight = (referenceBaseHeight + height) / 2;
            }
            Vector3 centroid = new Vector3();

                Vector3 position;
                RaycastHit hit;
                for (int a = 0; a < w.nodes.Count; a++)
                {
                    yield return null;
                    Node n = w.nodes[a];
                    position = new Vector3((float)((n.easthing - mcl.offsetPositionX) / MapChunkLoader.precision), 5000, (float)((n.northing - mcl.offsetPositionZ) / MapChunkLoader.precision));
                    float castH = 0;

                    if (Physics.Raycast(position, -Vector3.up, out hit, Mathf.Infinity, mcl.layerMask))
                    {
                        castH = hit.point.y;
                    }
                    nodes[a] = new Vector3(position.x, castH + height, position.z);
                    xz[a] = new Vector2(position.x, position.z);
                    centroid += nodes[a];
                }
                centroid /= w.nodes.Count;
                centroid.y += 1;

            Vector2[] xzRoof = new Vector2[w.nodes.Count -1];

            for (int a = 0; a < xzRoof.Length; a++)
            {
                xzRoof[a] = xz[a];
            }
            int[] indices;
            Vector3[] roofNodes;
            if (nodes.Length != 5 && nodes.Length != 6 && nodes.Length != 7 && nodes.Length != 8)
             {
                 Triangulator tr = new Triangulator(xzRoof);

                 int[] tempIndices = tr.Triangulate();
                 indices = tempIndices;
                 roofNodes = nodes;

             }
             else
             {
                 int[] tempIndices = new int[(nodes.Length-1)*3];
                 Vector3 midpoint = new Vector3();

                 for (int i = 0; i < nodes.Length-1; i++)
                 {
                     midpoint.x += nodes[i].x;
                     midpoint.y += nodes[i].y;
                     midpoint.z += nodes[i].z;
                 }

                 roofNodes = new Vector3[nodes.Length];
                 midpoint.x = midpoint.x / (nodes.Length-1);
                 midpoint.y = midpoint.y / (nodes.Length - 1) + height/5;
                 midpoint.z = midpoint.z / (nodes.Length - 1);

                 for (int i = 0; i < roofNodes.Length - 1; i++)
                 {
                     roofNodes[i] = nodes[i];
                 }

                 roofNodes[roofNodes.Length - 1] = midpoint;

                Triangle test = new Triangle();
                 test.a = roofNodes[0];
                 test.b = roofNodes[1];
                 test.c = roofNodes[4];
                 Vector3 testVector = test.Normal;

                 int u = 0;
                 for (int i = 0; i < roofNodes.Length - 2; i += 1)
                 {
                     if (testVector.y > 0)
                     {
                         tempIndices[u] = i;
                         tempIndices[u + 1] = i + 1;
                         tempIndices[u + 2] = roofNodes.Length - 1;
                     }
                     else
                     {
                         tempIndices[u + 1] = i;
                         tempIndices[u] = i + 1;
                         tempIndices[u + 2] = roofNodes.Length - 1;
                     }
                     u += 3;
                     if (u >= tempIndices.Length - 3)
                     {
                         i += 1;
                         if (testVector.y > 0)
                         {
                             tempIndices[u] = i;
                             tempIndices[u + 1] = 0;
                             tempIndices[u + 2] = roofNodes.Length - 1;
                         }
                         else
                         {
                             tempIndices[u + 1] = i;
                             tempIndices[u] = 0;
                             tempIndices[u + 2] = roofNodes.Length - 1;
                         }
                     }
                 }

                 indices = tempIndices;

             }
            // Create the mesh

            Vector2[] uvs = new Vector2[roofNodes.Length];
            for (int a = 0; a < roofNodes.Length; a++)
            {
                if (a < roofNodes.Length - 1)
                {
                    uvs[a] = new Vector2(a,0);
                }
                else
                {
                    uvs[a] = new Vector2(a/2, 1);
                }
            }

            roofm.vertices = roofNodes;
            roofm.triangles = indices;
            roofm.uv = uvs;
            roofm.RecalculateNormals();
            roofm.RecalculateBounds();

            // Set up game object with mesh;
                centroid = new Vector3(centroid.x, centroid.y, centroid.z);
                wallsm = BuildingCountourMesh(nodes, wallsm, height);

                if (w.name != null)
                {
                    GameObject label = new GameObject();
                    FloatingLabel lb = label.AddComponent<FloatingLabel>();
                    lb.transform.parent = roof.transform;
                    lb.text = w.name;
                    lb.target = GameObject.FindGameObjectWithTag("Player").transform;
                    lb.transform.position = centroid;
                }
                build.transform.parent = mcl.transform;
                walls.transform.parent = build.transform;
                roof.transform.parent = build.transform;

              //Wall
                filter.sharedMesh = wallsm;
               // wallmc.sharedMesh = wallsm;

              //Roof
                filter2.sharedMesh = roofm;
                //roofmc.sharedMesh = roofm;

                if (mcl.exportObjs)
                {
                    ObjExporter oe1 = new ObjExporter();
                    ObjExporter oe2 = new ObjExporter();
                    oe1.MeshToFile(filter, buildPath);
                    oe2.MeshToFile(filter2, roofPath);
                }
            }
            else
            {
                ObjImporter oi = new ObjImporter();
                mcl.StartCoroutine(oi.FileToMesh("file://" + buildPath));

                while (oi._myMesh == null)
                {
                    yield return null;
                }

                filter.sharedMesh = oi._myMesh;
                Debug.LogWarning("Loaded Walls from cache " + buildPath);

                ObjImporter oi2 = new ObjImporter();
                mcl.StartCoroutine(oi2.FileToMesh("file://" + roofPath));

                while (oi2._myMesh == null)
                {
                    yield return null;
                }

                filter2.sharedMesh = oi2._myMesh;
                Debug.LogWarning("Loaded Roof from cache " + roofPath);
            }

        /*if (w.height != 0)
        {
            walls.GetComponent<MeshRenderer>().material = Resources.Load("Materials/Real Height Material") as Material;
        }
        else*/
        {
            int textureIndex = UnityEngine.Random.Range(1,4);

            walls.GetComponent<MeshRenderer>().material = Resources.Load("Materials/BuildingMaterial" + textureIndex) as Material;
        }
        /*if (w.height != 0)
        {
            roof.GetComponent<MeshRenderer>().material = Resources.Load("Materials/Real Height Material") as Material;
        }
        else*/
        {
            int textureIndex = UnityEngine.Random.Range(1, 3);
            roof.GetComponent<MeshRenderer>().material = Resources.Load("Materials/Roof" + textureIndex) as Material;
        }
    }
Exemplo n.º 31
0
 public static void SaveObjToDisk(MeshFilter meshFilter, string filePath)
 {
     ObjExporter.MeshToFile(meshFilter, filePath);
 }
Exemplo n.º 32
0
    public override IEnumerator Build(Way w, MapChunkLoader mcl)
    {
        //GameObject go = new GameObject();
        //go.name = "Road";

        GameObject road = new GameObject();
        road.name = "Road - " + w.id.ToString();
        road.isStatic = true;
        road.transform.parent = mcl.transform;
        string roadPath = Application.persistentDataPath + "Assets/Resources/Objs/" + road.name + ".obj";

        if (!File.Exists(roadPath)) // If the file isn't cached we calculate everything and then we cache it
        {
            Debug.Log("STARTED CREATING ROAD");
            PolyLine pl = new PolyLine(w.id.ToString());
            pl.SetOffset(mcl.offsetPositionX, mcl.offsetPositionZ);
            pl.heigth = w.height;

            if (w.type == WayType.Footway)
            {
                pl.material = Resources.Load("Materials/Footway Material") as Material;
                pl.width = 1;
            }
            if (w.type == WayType.Motorway)
            {
                pl.material = Resources.Load("Materials/Road Material") as Material;
                pl.width = 4;
                pl.lanes = 2;
            }
            if (w.type == WayType.Residential)
            {
                pl.material = Resources.Load("Materials/Road Material") as Material;
                pl.width = 2;
            }
            if (w.type == WayType.River)
            {
                pl.material = Resources.Load("Materials/River Material") as Material;
                pl.width = 8;
            }

            for (int a = 0; a < w.nodes.Count; a++)
            {
                Node n = w.nodes[a];

                Vector3 position = new Vector3((float)(n.easthing - mcl.offsetPositionX), 5000, (float)(n.northing - mcl.offsetPositionZ));
                float baseHeight = 0;
                RaycastHit hit;

                if (Physics.Raycast(position, -Vector3.up, out hit, Mathf.Infinity, mcl.layerMask))
                {
                    baseHeight = hit.point.y;
                }
                n.height = baseHeight;
                pl.Add(n);

            }
            //Closed road;
            mcl.StartCoroutine(pl.Close(road));

            if (mcl.exportObjs)
            {
                while (road.GetComponent<MeshFilter>() == null)
                {
                    yield return null;
                }
                MeshFilter mf = road.GetComponent<MeshFilter>();
                ObjExporter oe = new ObjExporter();
                oe.MeshToFile(mf, roadPath);

            }
        }
        else
        {
            ObjImporter oi = new ObjImporter();
            mcl.StartCoroutine(oi.FileToMesh("file://" + roadPath));
            while (oi._myMesh == null)
            {
                yield return null;

            }
            MeshFilter mf = road.AddComponent<MeshFilter>();
            MeshRenderer mr = road.AddComponent<MeshRenderer>();
            mf.sharedMesh = oi._myMesh;
            Debug.LogWarning("Loaded Road from cache " + roadPath);
            if (w.type == WayType.Footway)
            {
                mr.material = Resources.Load("Materials/Footway Material") as Material;

            }
            if (w.type == WayType.Motorway)
            {
                mr.material = Resources.Load("Materials/Road Material") as Material;

            }
            if (w.type == WayType.Residential)
            {
                mr.material = Resources.Load("Materials/Road Material") as Material;

            }
            if (w.type == WayType.River)
            {
                mr.material = Resources.Load("Materials/River Material") as Material;

            }
        }
    }
Exemplo n.º 33
0
    public override IEnumerator Build(Way w, MapChunkLoader mcl)
    {
        Vector3[] nodes = new Vector3[w.nodes.Count];
        Vector2[] xz = new Vector2[w.nodes.Count];

        float height = 0;

        mcl.mapManager.mapHash.Add(w.id);
        mcl.wayList.Add(w.id);
        GameObject roof = new GameObject();
        // roof.transform.position = new Vector3(0, centroid.y, 0);
        roof.name = "Area - " + (2 * w.id).ToString();
        mcl.mapManager.mapHash.Add(2 * w.id);
        mcl.wayList.Add(2 * w.id);
        roof.isStatic = true;
        if (w.name != null)
        {
            GameObject label = new GameObject();
            FloatingLabel lb = label.AddComponent<FloatingLabel>();
            lb.text = w.name;
            //lb.transform.position = centroid;
            lb.target = GameObject.FindGameObjectWithTag("Player").transform;
            label.transform.parent = roof.transform;
        }
        roof.transform.parent = mcl.transform;
        Mesh roofm = new Mesh();
        roof.AddComponent<MeshRenderer>();
        MeshFilter filter2 = roof.AddComponent<MeshFilter>();
        roof.AddComponent<MeshCollider>();

        string areaPath = Application.persistentDataPath + "Assets/Resources/Objs/" + roof.name + ".obj";

        if (!File.Exists(areaPath)) // If the file isn't cached we calculate everything and then we cache it
        {

            if (w.height != 0)
                height = w.height;

            Vector3 centroid = new Vector3();
            for (int a = 0; a < w.nodes.Count; a++)
            {
                yield return null;
                RaycastHit hit;
                Node n = w.nodes[a];
                nodes[a] = new Vector3((float)((n.easthing - mcl.offsetPositionX) / MapChunkLoader.precision), 5000, (float)((n.northing - mcl.offsetPositionZ) / MapChunkLoader.precision));
                if (Physics.Raycast(nodes[a], -Vector3.up, out hit, Mathf.Infinity, mcl.layerMask))
                {
                    nodes[a].y = hit.point.y + height + 0.5f;
                }
                else
                {
                    nodes[a].y = 1;
                }
                xz[a] = new Vector2((float)((n.easthing - mcl.offsetPositionX) / MapChunkLoader.precision), (float)((n.northing - mcl.offsetPositionZ) / MapChunkLoader.precision));
                centroid += nodes[a];
            }
            centroid /= w.nodes.Count;
            centroid.y += 1;

            //  Vector3 position = new Vector3(centroid.x, 5000, centroid.z);
            float baseHeight = 0;

            /*RaycastHit hit;
            if (Physics.Raycast(position, -Vector3.up, out hit, Mathf.Infinity, layerMask))
            {
                baseHeight = hit.point.y;
            }*/
            //centroid = new Vector3(centroid.x, centroid.y + baseHeight, centroid.z);

            Vector2[] xzRoof = new Vector2[w.nodes.Count - 1];

            for (int a = 0; a < xzRoof.Length; a++)
            {
                xzRoof[a] = xz[a];
            }

            Triangulator tr = new Triangulator(xzRoof);

            int[] indices = tr.Triangulate();
            // Create the mesh

            roofm.vertices = nodes;
            roofm.triangles = indices;

            Vector2[] uvs = new Vector2[nodes.Length];
            for (int a = 0; a < nodes.Length; a++)
            {
                if (a < nodes.Length - 1)
                {
                    uvs[a] = new Vector2(Mathf.Abs(nodes[a].x) / nodes[nodes.Length - 1].x, Mathf.Abs(nodes[a].z) / nodes[nodes.Length - 1].x);
                }
                else
                {
                    uvs[a] = new Vector2(1, 1);
                }
            }

            roofm.uv = uvs;
            roofm.RecalculateNormals();
            roofm.RecalculateBounds();
            filter2.sharedMesh = roofm;

            if (mcl.exportObjs)
            {
                ObjExporter oe = new ObjExporter();
                oe.MeshToFile(filter2, areaPath);
            }
        }
        else
        {
            ObjImporter oi = new ObjImporter();
            mcl.StartCoroutine(oi.FileToMesh("file://" + areaPath));
            while (oi._myMesh == null)
            {
                yield return null;
            }

            filter2.sharedMesh = oi._myMesh;
            Debug.LogWarning("Loaded Area from cache " + areaPath);
        }

        if (w.type == WayType.Parking)
            roof.GetComponent<MeshRenderer>().material = Resources.Load("Materials/Parking Material") as Material;
        if (w.type == WayType.Park)
            roof.GetComponent<MeshRenderer>().material = Resources.Load("Materials/Park Material") as Material;
        if (w.type == WayType.RiverBank)
            roof.GetComponent<MeshRenderer>().material = Resources.Load("Materials/River Material") as Material;
    }
    public IEnumerator FusionSelection()
    {
        //Wait for object selection or cancel
        while (fusionList.Count != 2 && this.FusionPanel.activeInHierarchy)
        {
            yield return(new WaitForSeconds(0.001f));
        }
        //Do merge
        if (fusionList.Count == 2)
        {
            GameObject GO1 = GameObject.Find(fusionList.Keys[0]);
            GameObject GO2 = GameObject.Find(fusionList.Keys[1]);
            Debug.Log("MERGING " + GO1.name + " AND " + GO2.name);
            if (GeomUtils.Intersects(GO1, GO2))
            {
                Debug.Log("INTERSECTS");
                string GO1Off = ObjectFileFormat.MeshToOff(GO1.GetComponent <MeshFilter>().mesh, GO1.transform);
                string GO2Off = ObjectFileFormat.MeshToOff(GO2.GetComponent <MeshFilter>().mesh, GO2.transform);

                System.IntPtr GO1Ptr          = Marshal.StringToHGlobalAnsi(GO1Off);
                IntPtr        GO2Ptr          = Marshal.StringToHGlobalAnsi(GO2Off);
                String        matrix1         = GeomUtils.GetTransformationMatrix(GO1.transform, 0f, 0f, 0f);
                String        matrix2         = GeomUtils.GetTransformationMatrix(GO1.transform, 0f, 0f, 0f);
                IntPtr        GO1TransformPtr = Marshal.StringToHGlobalAnsi(matrix1);
                IntPtr        GO2TransformPtr = Marshal.StringToHGlobalAnsi(matrix2);

                IntPtr ptrResult = CGALPlugin.BooleanOperationClean(GO1Ptr, GO1TransformPtr, GO2Ptr, GO2TransformPtr, Marshal.StringToHGlobalAnsi("union"));
                string result    = Marshal.PtrToStringAnsi(ptrResult);

                //exportOff

                /*StreamWriter SW = new StreamWriter(SceneManager.DataPath + "Fusion-" + DateTime.Now.ToString("hhmmss") + (Time.deltaTime * 1000) + ".off");
                 * SW.Write(result);
                 * SW.Close();*/

                // Open string stream on the result off string
                byte[]       byteArray = Encoding.UTF8.GetBytes(result);
                MemoryStream stream    = new MemoryStream(byteArray);

                //Convert off string to Mesh and add it to scene
                Mesh myMesh = ObjectFileFormat.OffToMesh(new StreamReader(stream));
                stream.Close();
                myMesh.RecalculateNormals();

                //Export obj file
                ObjExporter.MeshToFile(myMesh, "Fusion-" + DateTime.Now.ToString("hhmmssffff"), "BenchMat");

                //Add mesh to scene
                GeomUtils.AddMeshToScene("Fusion-" + DateTime.Now.ToString("hhmmssffff"), myMesh, Vector3.zero, objectContainer.transform);

                //Destroy previous previous meshes
                Destroy(GO1.transform.parent.gameObject);
                Destroy(GO2.transform.parent.gameObject);
            }
            //Not intersecting
            else
            {
                SceneManager.instance.errorMesage.text = "Selected objects are not overlapped !";
            }

            ResetFusionSelection();
        }
    }