Inheritance: MonoBehaviour
示例#1
0
        private static ToolResult DeleteUnusedMaterialsObj(string objFile, string objOutput)
        {
            bool    success = false;
            string  message = "";
            ObjData objData = ObjParser.TryParseObj(objFile);

            if (objData != null)
            {
                objData.UpdateMtlData();
                MtlData mtlData = objData.Mtl;
                if (mtlData != null)
                {
                    ObjModifier.DeleteUnusedMaterials(objData, mtlData);
                    success = ObjExporter.WriteObj(objData, mtlData, objOutput, makeMtl: true, useExistingMtl: true);
                    message = MessageBoxConstants.GetMessageExecutionCreation(success, objOutput);
                }
                else
                {
                    message = MessageBoxConstants.MessageErrorDeleteUnusedMaterials +
                              MessageBoxConstants.MessageMtlNotFound;
                }
            }
            else
            {
                message = MessageBoxConstants.GetMessageExecutionErrorParse(objFile);
            }
            return(new ToolResult(message, success));
        }
示例#2
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;
    }
示例#3
0
        private static ToolResult MergeObjFiles(List <string> fileList, string objOutput)
        {
            bool          success = false;
            StringBuilder sb      = new StringBuilder();

            if (fileList != null)
            {
                List <ObjData> objDatas = ObjParser.ParseObjs(fileList);
                ObjData        objData  = ObjModifier.MergeObjFiles(objDatas);
                if (objData != null)
                {
                    success = ObjExporter.WriteObj(objData, objData.Mtl, objOutput, makeMtl: true, useExistingMtl: true);
                    sb.AppendLine($"Merged {objDatas.Count} obj files into one");
                    sb.Append(MessageBoxConstants.GetMessageExecutionCreation(success, objOutput));
                }
                else
                {
                    sb.Append(MessageBoxConstants.MessageErrorMergeObj + MessageBoxConstants.MessageErrorExecution);
                }
            }
            else
            {
                sb.Append(MessageBoxConstants.MessageErrorMergeObj + MessageBoxConstants.MessageNoFilesMerge);
            }
            return(new ToolResult(sb.ToString(), success));
        }
示例#4
0
    public void Export()
    {
        GameObject generator = this.gameObject;

        Combiner.CombineMeshes(generator);
        ObjExporter.MeshesToFile(generator.GetComponents <MeshFilter>(), Application.dataPath, "Planet");
    }
示例#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");
        }
    }
示例#6
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;
    }
示例#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();
    }
示例#8
0
        public void Export_SimpleModel_ValidOutput()
        {
            string path    = "temp.obj";
            string mtlPath = Path.ChangeExtension(path, ".mtl");

            try
            {
                var e = new ObjExporter {
                    MaterialsFile = mtlPath
                };
                using (var stream = File.Create(path))
                {
                    this.ExportSimpleModel(e, stream);
                }
            }
            finally
            {
                if (File.Exists(path))
                {
                    File.Delete(path);
                }

                if (File.Exists(mtlPath))
                {
                    File.Delete(mtlPath);
                }
            }
        }
示例#9
0
        public void Export_BoxWithGradientTexture_TextureExportedAsPng()
        {
            var path    = "box_gradient_png.obj";
            var mtlPath = Path.ChangeExtension(path, ".mtl");

            try
            {
                var e = new ObjExporter {
                    MaterialsFile = mtlPath
                };
                using (var stream = File.Create(path))
                {
                    this.ExportModel(e, stream, () => new BoxVisual3D {
                        Material = Materials.Rainbow
                    });
                }
            }
            finally
            {
                if (File.Exists(path))
                {
                    File.Delete(path);
                }

                if (File.Exists(mtlPath))
                {
                    File.Delete(mtlPath);
                }

                if (File.Exists("mat1.png"))
                {
                    File.Delete("mat1.png");
                }
            }
        }
示例#10
0
    public static void SerializedValues_AreCultureInvariant()
    {
        var cube    = GameObject.CreatePrimitive(PrimitiveType.Cube);
        var model   = new Model("Cube", cube.GetComponent <MeshFilter>().sharedMesh, cube.GetComponent <MeshRenderer>().sharedMaterial);
        var current = Thread.CurrentThread.CurrentCulture;

        try
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");

            string        obj, mtl;
            List <string> textures;

            if (ObjExporter.Export("Cube Test", new Model[] { model }, out obj, out mtl, out textures))
            {
                Assert.IsFalse(obj.Any(x => x.Equals(',')));
                Assert.IsFalse(mtl.Any(x => x.Equals(',')));
            }
        }
        finally
        {
            Thread.CurrentThread.CurrentCulture = current;
            UnityEngine.Object.DestroyImmediate(cube);
        }
    }
示例#11
0
        public static void ExportSingleCube_CreatesUnityReadableMeshFile()
        {
            var cube = ShapeGenerator.CreateShape(ShapeType.Cube);

            string        obj;
            string        mtl;
            List <string> textures;

            var res = ObjExporter.Export("Single cube",
                                         new Model[] { new Model("Single Cube Mesh", cube, true) },
                                         out obj,
                                         out mtl,
                                         out textures);

            Assume.That(res, Is.True);
            Assume.That(string.IsNullOrEmpty(obj), Is.False);
            Assume.That(string.IsNullOrEmpty(mtl), Is.False);

            string exportedPath = TestUtility.temporarySavedAssetsDirectory + "SingleCube.obj";

            File.WriteAllText(exportedPath, obj);
            AssetDatabase.ImportAsset(exportedPath);

            var imported = AssetDatabase.LoadAssetAtPath(exportedPath, typeof(Mesh)) as Mesh;

            Assume.That(imported, Is.Not.Null);

            Assert.That(imported.vertexCount, Is.GreaterThan(0));
        }
示例#12
0
    public static void ExportSingleCube_CreatesUnityReadableMeshFile(
        [ValueSource("k_Handedness")] ObjOptions.Handedness handedness,
        [ValueSource("k_CopyTextures")] bool copyTextures,
        [ValueSource("k_ApplyTransforms")] bool applyTransforms,
        [ValueSource("k_VertexColors")] bool vertexColors,
        [ValueSource("k_TextureOffsetScale")] bool textureOffsetScale
        )
    {
        var cube = ShapeGenerator.CreateShape(ShapeType.Cube);

        string        obj;
        string        mtl;
        List <string> textures;

        var res = ObjExporter.Export("Single cube",
                                     new Model[] { new Model("Single Cube Mesh", cube, true) },
                                     out obj,
                                     out mtl,
                                     out textures);

        Assume.That(res, Is.True);
        Assume.That(string.IsNullOrEmpty(obj), Is.False);
        Assume.That(string.IsNullOrEmpty(mtl), Is.False);

        string exportedPath = TestUtility.temporarySavedAssetsDirectory + "SingleCube.obj";

        File.WriteAllText(exportedPath, obj);
        AssetDatabase.ImportAsset(exportedPath);

        var imported = AssetDatabase.LoadAssetAtPath(exportedPath, typeof(Mesh)) as Mesh;

        Assume.That(imported, Is.Not.Null);
        Assert.That(imported.vertexCount, Is.GreaterThan(0));
    }
示例#13
0
 //
 // Static Methods
 //
 public static void MeshToFile(MeshFilter mf, string filename, float scale)
 {
     using (StreamWriter streamWriter = new StreamWriter(filename))
     {
         streamWriter.Write(ObjExporter.MeshToString(mf, scale));
     }
 }
    void ControlButtons()
    {
        Color defaultColor = GUI.backgroundColor;

        GUI.backgroundColor      = Color.green;
        generateButton.fontStyle = FontStyle.Bold;

        generateButton = "button";
        if (GUILayout.Button("Generate Building", generateButton, GUILayout.Width(130), GUILayout.Height(40)))
        {
            generatorController.Generate();
        }

        GUI.backgroundColor = defaultColor;
        generateButton      = "button";
        GUILayout.Space(5);

        GUILayout.BeginHorizontal();
        if (GUILayout.Button("Export", GUILayout.Width(130), GUILayout.Height(30)))
        {
            if (!String.IsNullOrEmpty(generatorController.path))
            {
                ObjExporter.DoExport(false, generatorController.parentObj, generatorController.path);
            }
        }
        if (GUILayout.Button("Merge Mesh", GUILayout.Width(130), GUILayout.Height(30)))
        {
            generatorController.Merge();
        }

        GUILayout.EndHorizontal();
    }
示例#15
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();
    }
示例#16
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);
                    }
                }
            }
        }
        private void OnUserRequestExportMeshes()
        {
            var sfd = new CommonSaveFileDialog();

            sfd.Title = "Save File...";
            sfd.AddToMostRecentlyUsedList = false;
            //sfd.EnsureFileExists = true;
            //sfd.EnsurePathExists = true;
            sfd.EnsureReadOnly   = false;
            sfd.EnsureValidNames = true;
            sfd.ShowPlacesList   = true;
            sfd.Filters.Add(new CommonFileDialogFilter("Obj Files", "*.obj"));
            sfd.Filters.Add(new CommonFileDialogFilter("All Files", "*.*"));

            if (sfd.ShowDialog() == CommonFileDialogResult.Ok)
            {
                string directoryName = Path.GetDirectoryName(sfd.FileName);
                Directory.CreateDirectory(directoryName);

                for (int i = 0; i < m_loadedModels.Count; i++)
                {
                    string exportName = Path.GetFileName(sfd.FileName);

                    // If they have more than one model currently loaded, export each obj
                    if (m_loadedModels.Count > 1)
                    {
                        exportName += string.Format("_{0}.obj", i.ToString("00"));
                    }

                    string exportPath = Path.Combine(directoryName, exportName);
                    ObjExporter.Export(m_loadedModels[i], exportPath);
                }
            }
        }
        static string DoExport(string path, IEnumerable <Model> models, ObjOptions options)
        {
            string name      = Path.GetFileNameWithoutExtension(path);
            string directory = Path.GetDirectoryName(path);

            List <string> textures = null;
            string        obj, mat;

            if (ObjExporter.Export(name, models, out obj, out mat, out textures, options))
            {
                try
                {
                    FileUtility.WriteAllText(string.Format("{0}/{1}.obj", directory, name), obj);
                    FileUtility.WriteAllText(string.Format("{0}/{1}.mtl", directory, name.Replace(" ", "_")), mat);
                    CopyTextures(textures, directory);
                }
                catch (System.Exception e)
                {
                    Debug.LogWarning(string.Format("Failed writing obj to path: {0}\n{1}", string.Format("{0}/{1}.obj", path, name), e.ToString()));
                    return(null);
                }
            }
            else
            {
                Debug.LogWarning("No meshes selected.");
                return(null);
            }

            return(path);
        }
 // 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;
     }
 }
示例#20
0
        private void Start()
        {
            if (meshWrapper == null)
            {
                return;
            }

            var menu = new Settings.Menu(Tools.ToolType.Standard);

            if (sculptors != null)
            {
                foreach (var sculptor in sculptors)
                {
                    sculptor.Init(meshWrapper.SculptMesh, menu);
                }
            }

            menu.ExportAction.OnDone += () =>
            {
                ObjExporter.Export(
                    meshWrapper.SculptMesh.Mesh,
                    meshWrapper.MeshTransform
                    );
            };
        }
示例#21
0
 // Update is called once per frame
 void Update()
 {
     if (save)
     {
         ObjExporter.MeshToFile(targetObject, targetObject.name + ".obj");
         save = false;
     }
 }
 public void ShouldThrowExceptionIfMaterialsFileIsNotSpecified()
 {
     string path = "temp.obj";
     var e = new ObjExporter();
     using (var stream = File.Create(path))
     {
         Assert.Throws<InvalidOperationException>(() => this.ExportSimpleModel(e, stream));
     }
 }
示例#23
0
        public void Export_SimpleModel_ValidOutput()
        {
            string path = "temp.obj";

            using (var e = new ObjExporter(path))
            {
                ExportSimpleModel(e);
            }
        }
示例#24
0
 public void Save()
 {
     foreach (Body body in bodiesToExport)
     {
         string name = "Bakes/" + exportName + "/_" + body.gameObject.name;
         body.Bake();
         ObjExporter.Save(name, body.mesh);
     }
 }
 public void Export_BoxWithGradientTexture_TextureExportedAsPng()
 {
     var path = "box_gradient_png.obj";
     var e = new ObjExporter { MaterialsFile = Path.ChangeExtension(path, ".mtl") };
     using (var stream = File.Create(path))
     {
         this.ExportModel(e, stream, () => new BoxVisual3D { Material = Materials.Rainbow });
     }
 }
 public void Export_SimpleModel_ValidOutput()
 {
     string path = "temp.obj";
     var e = new ObjExporter { MaterialsFile = Path.ChangeExtension(path, ".mtl") };
     using (var stream = File.Create(path))
     {
         this.ExportSimpleModel(e, stream);
     }
 }
示例#27
0
 private void SaveMeshes(string outputFolder)
 {
     for (int i = 0; i < displays.Length; i++)
     {
         GameObject obj        = displays[i].gameObject;
         string     outputPath = outputFolder + i + ".obj";
         ObjExporter.GameObjectToFile(obj, i, outputPath);
     }
 }
示例#28
0
 private void SaveStrokeData(string baseFilename)
 {
     if (saveOBJ)
     {
         // save as OBJ
         ObjExporter.SaveMeshes(strokeContainer, baseFilename);
     }
     strokeList.SaveStrokeData(baseFilename);
 }
示例#29
0
        private void ExportModel(string fileName = "model.obj")
        {
            using (var exporter = new ObjExporter(fileName))
            {
                exporter.Export(this.Model);
            }

            Process.Start("explorer.exe", "/select,\"" + fileName + "\"");
        }
示例#30
0
 public override void OnInspectorGUI()
 {
     base.OnInspectorGUI();
     if (GUILayout.Button("Button"))
     {
         RotModel obj = (RotModel)target;
         ObjExporter.MeshToFile(obj.Gc <MeshFilter>(), "Assets/" + obj.name + ".obj");
     }
 }
示例#31
0
        public void Export_SimpleModel_ValidOutput()
        {
            string path = "temp.obj";
            var    e    = new ObjExporter();

            using (var stream = File.Create(path))
            {
                this.ExportSimpleModel(e, stream);
            }
        }
示例#32
0
        public void ShouldThrowExceptionIfMaterialsFileIsNotSpecified()
        {
            string path = "temp.obj";
            var    e    = new ObjExporter();

            using (var stream = File.Create(path))
            {
                Assert.Throws <InvalidOperationException>(() => this.ExportSimpleModel(e, stream));
            }
        }
    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");
        }
    }
    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;
        }
    }
示例#35
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;

            }
        }
    }
示例#36
0
        public Result Execute(
      ExternalCommandData commandData,
      ref string message,
      ElementSet elements )
        {
            UIApplication uiapp = commandData.Application;
              UIDocument uidoc = uiapp.ActiveUIDocument;
              Application app = uiapp.Application;
              Document doc = uidoc.Document;

              // Determine elements to export

              FilteredElementCollector collector = null;

              // Access current selection

              SelElementSet set = uidoc.Selection.Elements;

              int n = set.Size;

              if( 0 < n )
              {
            // If any elements were preselected,
            // export those to OBJ

            ICollection<ElementId> ids = set
              .Cast<Element>()
              .Select<Element, ElementId>( e => e.Id )
              .ToArray<ElementId>();

            collector = new FilteredElementCollector( doc, ids );
              }
              else
              {
            // If nothing was preselected, export
            // all model elements to OBJ

            collector = new FilteredElementCollector( doc );
              }

              collector.WhereElementIsNotElementType()
              .WhereElementIsViewIndependent();

              if( null == _export_folder_name )
              {
            _export_folder_name = Path.GetTempPath();
              }

              string filename = null;

              if( !FileSelect( _export_folder_name,
            out filename ) )
              {
            return Result.Cancelled;
              }

              _export_folder_name
            = Path.GetDirectoryName( filename );

              ObjExporter exporter = new ObjExporter();

              Options opt = app.Create.NewGeometryOptions();

              ExportElements( exporter, collector, opt );

              exporter.ExportTo( filename );

              return Result.Succeeded;
        }
    // 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();
    }
示例#38
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;
    }