Exemplo n.º 1
0
        public FromOBJRenderable()
        {
            var obj = FileFormatObj.Load(GetAssetPath(), true);

            List <Vector3> vertList  = new List <Vector3>();
            List <Vector2> uvList    = new List <Vector2>();
            List <uint>    indexList = new List <uint>();

            foreach (var face in obj.Model.UngroupedFaces)
            {
                foreach (var index in face.Indices)
                {
                    var vert = obj.Model.Vertices[index.vertex];
                    var uv   = obj.Model.Uvs[index.uv.Value];

                    vertList.Add(
                        new Vector3(vert.x, vert.y, vert.z)
                        );

                    uvList.Add(
                        new Vector2(uv.u, uv.v)
                        );

                    indexList.Add((uint)indexList.Count);
                }
            }

            verts    = vertList.ToArray();
            uvCoords = uvList.ToArray();
            indices  = indexList.ToArray();
        }
Exemplo n.º 2
0
 public FigureFromOBJ(OpenGL gl, ColorF color, Point3D position, string fileName, Texture texture = null, float scale = 1)
     : base(color, position)
 {
     result       = FileFormatObj.Load(fileName);
     this.texture = texture;
     this.scale   = scale;
     ListInd      = gl.GenLists(1);
     gl.NewList(ListInd, OpenGL.GL_COMPILE);
     {
         DrawFigure(gl);
     }
     gl.EndList();
 }
Exemplo n.º 3
0
        static int Main(string[] args)
        {
            //  Get the path.
            if (args.Length < 1 || string.IsNullOrWhiteSpace(args[0]))
            {
                Console.WriteLine("Please provide a path to an *.obj file.");
                return(1);
            }

            //  Use the File Format object to load the test data.
            var result = FileFormatObj.Load(args[0]);

            //  If there are no messages, then the file is completely valid.
            if (!result.Messages.Any())
            {
                Console.WriteLine("The file loaded with no validation errors or warnings.");
            }

            //  Show each message.
            foreach (var message in result.Messages)
            {
                Console.WriteLine("{0}: {1}", message.MessageType, message.Details);
                Console.WriteLine("{0}: {1}", message.FileName, message.LineNumber);
            }

            Console.WriteLine("Complete. Loaded:");
            Console.WriteLine("  Vertices: {0}", result.Model.Vertices.Count);
            Console.WriteLine("  UVS: {0}", result.Model.Uvs.Count);
            Console.WriteLine("  Normals: {0}", result.Model.Normals.Count);
            Console.WriteLine("  Ungrouped Faces: {0}", result.Model.UngroupedFaces.Count);
            Console.WriteLine("  Groups: {0}", result.Model.Groups.Count);
            Console.WriteLine("  Faces in Groups: {0}", result.Model.Groups.Select(g => g.Faces.Count).Sum());
            Console.WriteLine("  Materials: {0}", result.Model.Materials.Count);
            Console.WriteLine("with:");
            Console.WriteLine("  Warnings: {0}", result.Messages.Count(m => m.MessageType == MessageType.Warning));
            Console.WriteLine("  Errors: {0}", result.Messages.Count(m => m.MessageType == MessageType.Error));

            Console.WriteLine("Any key to close.");
            Console.ReadKey();

            return(0);
        }
Exemplo n.º 4
0
        private async void LoadFileAsync(string path)
        {
            //  Reset the UI.
            DestroyDetailsUi();
            treeViewModel.Nodes.Clear();

            //  Create a loading message, write it and set the app to busy.
            var loadingMessage = string.Format("Loading {0}", Path.GetFileName(path));

            AddOutput(loadingMessage);
            StartBusy(loadingMessage);

            //  Start a stopwatch for the actual loading.
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            //  Load the model.
            var result = await Task.Run(() => FileFormatObj.Load(path, true));

            StopBusy();
            stopwatch.Stop();

            //  Write a little bit of summary information.
            AddOutput(string.Format("Loaded {0} in {1}, {2} warning(s), {3} error(s).",
                                    Path.GetFileName(path),
                                    stopwatch.Elapsed,
                                    result.Messages.Count(m => m.MessageType == MessageType.Warning),
                                    result.Messages.Count(m => m.MessageType == MessageType.Error)));
            if (!string.IsNullOrEmpty(result.Model.ObjectName))
            {
                AddOutput(string.Format("The object is named '{0}'.", result.Model.ObjectName));
            }

            //  Show the result.
            ShowResult(result);
        }
Exemplo n.º 5
0
        public void Load(string path)
        {
            FileLoadResult <FileFormatWavefront.Model.Scene> fileLoadResult = FileFormatObj.Load(path, false);

            if (fileLoadResult.Model != null)
            {
                _objectName = fileLoadResult.Model.ObjectName;

                List <Vector3> buffer00 = new List <Vector3>();
                for (int i = 0; i < fileLoadResult.Model.Vertices.Count; i++)
                {
                    buffer00.Add(new Vector3(
                                     fileLoadResult.Model.Vertices[i].x,
                                     fileLoadResult.Model.Vertices[i].y,
                                     fileLoadResult.Model.Vertices[i].z));
                }
                vertice = buffer00.ToArray();

                buffer00 = new List <Vector3>();
                for (int i = 0; i < fileLoadResult.Model.Normals.Count; i++)
                {
                    buffer00.Add(new Vector3(
                                     fileLoadResult.Model.Normals[i].x,
                                     fileLoadResult.Model.Normals[i].y,
                                     fileLoadResult.Model.Normals[i].z));
                }
                normal = buffer00.ToArray();

                List <Vector2> buffer01 = new List <Vector2>();
                for (int i = 0; i < fileLoadResult.Model.Uvs.Count; i++)
                {
                    buffer01.Add(new Vector2(
                                     fileLoadResult.Model.Uvs[i].u,
                                     fileLoadResult.Model.Uvs[i].v));
                }
                textureCoordinate = buffer01.ToArray();

                List <List <EFace> > buffer02 = new List <List <EFace> >();
                for (int i = 0; i < fileLoadResult.Model.UngroupedFaces.Count; i++)
                {
                    buffer02.Add(new List <EFace>());
                    for (int j = 0; j < fileLoadResult.Model.UngroupedFaces[i].Indices.Count; j++)
                    {
                        buffer02[i].Add(new EFace()
                        {
                            vertex = fileLoadResult.Model.UngroupedFaces[i].Indices[j].vertex,
                            normal = fileLoadResult.Model.UngroupedFaces[i].Indices[j].normal,
                            uv     = fileLoadResult.Model.UngroupedFaces[i].Indices[j].uv,
                        });
                    }
                }

                faces = new EFace[buffer02.Count][];
                for (int i = 0; i < buffer02.Count; i++)
                {
                    faces[i] = buffer02[i].ToArray();
                }
            }

            Compile();
        }
Exemplo n.º 6
0
        /// <summary>
        /// External command mainline.
        /// </summary>
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            IWin32Window revit_window
                = new JtWindowHandle(Autodesk.Windows
                                     .ComponentManager.ApplicationWindow);

            if (!Util.FileSelectObj(
                    Config.DefaultFolderObj,
                    ref _filename))
            {
                return(Result.Cancelled);
            }

            Config.DefaultFolderObj
                = Path.GetDirectoryName(_filename);

            long fileSize = Util.GetFileSize(_filename);

            if (fileSize > Config.MaxFileSize)
            {
                string msg = string.Format("Excuse me, but "
                                           + "you are attempting to load a file that is "
                                           + "{0} bytes in size. We suggest ensuring "
                                           + "that the file size is no larger than {1} "
                                           + "bytes, since Revit will refuse to handle "
                                           + "meshes exceeding a certain size anyway. "
                                           + "Please refer to the troubleshooting page "
                                           + "at\r\n\r\n{2}\r\n\r\n"
                                           + "for suggestions on how to optimise the "
                                           + "mesh and thus reduce file size.",
                                           fileSize, Config.MaxFileSize,
                                           TroubleshootingUrl);

                TaskDialog.Show(App.Caption, msg);

                return(Result.Failed);
            }

            FileLoadResult <Scene> obj_load_result = null;
            List <XYZ>             vertices        = null;

            try
            {
                bool loadTextureImages = true;

                obj_load_result = FileFormatObj.Load(
                    _filename, loadTextureImages);

                foreach (var m in obj_load_result.Messages)
                {
                    Debug.Print("{0}: {1} line {2} in {3}",
                                m.MessageType, m.Details,
                                m.FileName, m.LineNumber);
                }

                // Convert OBJ vertices to Revit XYZ.
                // OBJ assumes X to the right, Y up and Z out of the screen.
                // Revit 3D view assumes X right, Y away
                // from the screen and Z up.

                double scale = Config.InputScaleFactor;

                int n = obj_load_result.Model.Vertices.Count;

                vertices = new List <XYZ>(n);
                XYZ w;

                foreach (Vertex v in obj_load_result.Model.Vertices)
                {
                    w = new XYZ(v.x * scale,
                                -v.z * scale, v.y * scale);

                    Debug.Print("({0},{1},{2}) --> {3}",
                                Util.RealString(v.x),
                                Util.RealString(v.y),
                                Util.RealString(v.z),
                                Util.PointString(w));

                    vertices.Add(w);
                }

                foreach (Face f in obj_load_result.Model.UngroupedFaces)
                {
                    n = f.Indices.Count;

                    Debug.Assert(3 == n || 4 == n,
                                 "expected triangles or quadrilaterals");

                    Debug.Print(string.Join(", ",
                                            f.Indices.Select <Index, string>(
                                                i => i.vertex.ToString())));
                }
            }
            catch (System.Exception ex)
            {
                message = string.Format(
                    "Exception reading '{0}':"
                    + "\r\n{1}:\r\n{2}",
                    _filename,
                    ex.GetType().FullName,
                    ex.Message);

                return(Result.Failed);
            }

            if (vertices.Count > Config.MaxNumberOfVertices)
            {
                string msg = string.Format("Excuse me, but "
                                           + "you are attempting to load a mesh defining "
                                           + "{0} vertices. We suggest using no more than "
                                           + "{1}, since Revit will refuse to handle such "
                                           + "a large mesh anyway. "
                                           + "Please refer to the troubleshooting page at "
                                           + "\r\n\r\n{2}\r\n\r\n"
                                           + "for suggestions on how to optimise the mesh "
                                           + "and thus reduce its size.",
                                           vertices.Count, Config.MaxNumberOfVertices,
                                           TroubleshootingUrl);

                TaskDialog.Show(App.Caption, msg);

                return(Result.Failed);
            }

            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            string appGuid
                = uiapp.ActiveAddInId.GetGUID().ToString();

            string shapeName = Util.Capitalize(
                Path.GetFileNameWithoutExtension(_filename)
                .Replace('_', ' '));

            // Retrieve "<Sketch>" graphics style,
            // if it exists.

            FilteredElementCollector collector
                = new FilteredElementCollector(doc)
                  .OfClass(typeof(GraphicsStyle));

            GraphicsStyle style
                = collector.Cast <GraphicsStyle>()
                  .FirstOrDefault <GraphicsStyle>(gs
                                                  => gs.Name.Equals("<Sketch>"));

            ElementId graphicsStyleId = null;

            if (style != null)
            {
                graphicsStyleId = style.Id;
            }

            Result rc = Result.Failed;

            try
            {
                using (Transaction tx = new Transaction(doc))
                {
                    tx.Start("Create DirectShape from OBJ");

                    int nFaces      = 0; // set to -1 on fatal error
                    int nFacesTotal = 0;

                    if (0 < obj_load_result.Model.UngroupedFaces.Count)
                    {
                        nFacesTotal = nFaces = NewDirectShape(vertices,
                                                              obj_load_result.Model.UngroupedFaces, doc,
                                                              graphicsStyleId, appGuid, shapeName);
                    }

                    if (-1 < nFaces)
                    {
                        foreach (Group g in obj_load_result.Model.Groups)
                        {
                            string s = string.Join(".", g.Names);

                            if (0 < s.Length)
                            {
                                s = "." + s;
                            }

                            nFaces = NewDirectShape(vertices, g.Faces,
                                                    doc, graphicsStyleId, appGuid,
                                                    shapeName + s);

                            if (-1 == nFaces)
                            {
                                break;
                            }

                            nFacesTotal += nFaces;
                        }
                    }

                    if (-1 == nFaces)
                    {
                        message = "Invalid OBJ file. Error: face "
                                  + "vertex index exceeds total vertex count.";
                    }
                    else if (0 == nFacesTotal)
                    {
                        message = "Invalid OBJ file. Zero faces found.";
                    }
                    else
                    {
                        tx.Commit();

                        rc = Result.Succeeded;
                    }
                }
            }
            catch (System.Exception ex)
            {
                message = string.Format(
                    "Exception generating DirectShape '{0}':"
                    + "\r\n{1}:\r\n{2}",
                    shapeName,
                    ex.GetType().FullName,
                    ex.Message);

                return(Result.Failed);
            }
            return(rc);
        }
Exemplo n.º 7
0
        public WaveFrontRenderer(GraphicsDevice device, string file)
        {
            _effect = new BasicEffect(device);
            _effect.EnableDefaultLighting();
            _effect.PreferPerPixelLighting = false;

            var result = FileFormatObj.Load(device, file, true);

            foreach (var msg in result.Messages)
            {
                if (msg.Exception == null)
                {
                    Console.WriteLine($"File: {msg.FileName} - Details: {msg.Details}");
                }
                else
                {
                    Console.WriteLine($"File: {msg.FileName} - Exception: {msg.Exception.ToString()}");
                }
            }
            var vertices = result.Model.Vertices;
            var normals  = result.Model.Normals;
            var uvs      = result.Model.Uvs;

            /*Dictionary<string, BasicEffect> materials = new Dictionary<string, BasicEffect>();
             * foreach (var mat in result.Model.Materials)
             * {
             *      if (materials.ContainsKey(mat.Name)) continue;
             *
             *      var effect = new BasicEffect(device);
             *      {
             *              SetBasicEffect(ref effect, mat);
             *      }
             *
             *      materials.Add(mat.Name, effect);
             * }*/

            List <Group> groups = new List <Group>();

            foreach (var g in result.Model.Groups)
            {
                int textureCount = 0;
                List <VertexPositionNormalTexture> textures = new List <VertexPositionNormalTexture>();
                Group gr = new Group();
                gr.Name  = "";
                gr.Areas = new Areas[g.Faces.Count];

                for (var i = 0; i < g.Faces.Count; i++)
                {
                    var face = g.Faces[i];

                    VertexPositionNormalTexture[] faceVertices = new VertexPositionNormalTexture[face.Indices.Count];
                    for (var index = 0; index < face.Indices.Count; index++)
                    {
                        var indice = face.Indices[index];

                        var vert = vertices[indice.Vertex];

                        var v = new VertexPositionNormalTexture()
                        {
                            Position = vert
                        };

                        if (indice.Normal.HasValue)
                        {
                            var normal = normals[indice.Normal.Value];
                            v.Normal = normal;
                        }

                        if (indice.Uv.HasValue)
                        {
                            var uv = uvs[indice.Uv.Value];
                            v.TextureCoordinate = uv;
                        }

                        faceVertices[index] = v;
                    }

                    int startIndex = textureCount;
                    textures.AddRange(faceVertices);
                    textureCount += faceVertices.Length;

                    //	BasicEffect effect;
                    //if (!materials.TryGetValue(face.Material.Name, out effect))
                    //{
                    //	effect = new BasicEffect(device);
                    //	SetBasicEffect(ref effect, face.Material);
                    //}

                    Areas a = new Areas();
                    a.Material = face.Material;
                    //a.Effect = effect;
                    a.Length = faceVertices.Length;
                    a.Start  = startIndex;
                    a.Box    = BoundingSphere.CreateFromPoints(faceVertices.Select(x => x.Position));

                    if (face.Material.Transparency.HasValue)
                    {
                        if (face.Material.Transparency.Value < 1f)
                        {
                            a.HasTransparency = true;
                        }
                    }

                    gr.Areas[i] = a;
                }

                gr.Buffer = new VertexBuffer(device, VertexPositionNormalTexture.VertexDeclaration, textures.Count, BufferUsage.WriteOnly);
                gr.Buffer.SetData(textures.ToArray());

                groups.Add(gr);
            }

            Groups = groups.ToArray();
            //	Buffer = new VertexBuffer(device, VertexPositionNormalTexture.VertexDeclaration, textures.Count, BufferUsage.WriteOnly);
            //Buffer.SetData(textures.ToArray());
        }