Esempio n. 1
0
        private void addLayers(File3dm file, List <string> layers)
        {
            int          index  = 0;
            List <Color> colors = new List <Color> {
                Color.Black, Color.DarkBlue, Color.DarkGray, Color.DarkGray, Color.DarkOliveGreen, Color.DarkOrange, Color.DarkOrchid, Color.DarkSeaGreen, Color.DarkGoldenrod
            };

            foreach (string l in layers)
            {
                Layer layer = new Layer();
                layer.Name = l;
                if (l == "clippingplanes")
                {
                    layer.IsVisible = false;
                }
                layer.Color = System.Drawing.Color.Black;
                file.AllLayers.Add(layer);

                ObjectAttributes oa = new ObjectAttributes();
                oa.LayerIndex = index;

                oa.ObjectColor = colors[index];
                oa.Name        = l;
                objectAttributes.Add(oa);
                index++;
            }
        }
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            var path     = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            var filename = Path.Combine(path, "SampleCsWrite3dmFile.3dm");

            Result rc;

            using (var file = new File3dm())
            {
                var layer = new Layer {
                    Name = "Default", Color = Color.Black
                };
                file.AllLayers.Add(layer);

                var layer_index = file.AllLayers.Count - 1;
                var attributes  = new ObjectAttributes {
                    LayerIndex = layer_index
                };

                for (var x = 0; x < 100; x++)
                {
                    var line_curve = new LineCurve(new Point3d(x, 0, 0), new Point3d(x, 1, 0));
                    if (line_curve.IsValid)
                    {
                        file.Objects.AddCurve(line_curve, attributes);
                    }
                }

                rc = file.Write(filename, 6) ? Result.Success : Result.Failure;
            }

            return(rc);
        }
Esempio n. 3
0
        public void writeSection2d(MeshVoxeliser mvox)
        {
            File3dm file = setupFile();

            foreach (StructuralSpan sp in mvox.structuralSpans)
            {
                Point3d location = new Point3d();
                foreach (StructuralBay sb in sp.structuralBays)
                {
                    location.X = sb.baynum * 40000;
                    addBaySection2d(file, sb, location);
                }
            }
            RhinoViewport viewport = new RhinoViewport();

            viewport.SetProjection(DefinedViewportProjection.Top, "2d sections", false);
            viewport.ZoomExtents();
            file.AllViews.Add(new ViewInfo(viewport));
            string section = mvox.parameters.sectionNum.ToString();

            if (mvox.parameters.sectionNum < 10)
            {
                section = "0" + section;
            }
            file.Write(@"C:\Users\r.hudson\Documents\WORK\projects\passageProjects\sections\section" + section + "_2d.3dm", 5);
        }
Esempio n. 4
0
        public static bool ExportNestedBlock(NestedBlock nested, string filePath)
        {
            var doc = new File3dm();

            // Add all instance definitions
            foreach (var references in nested.GetRootTreeByRootDepth().Reverse())
            {
                var nameIndexDict = new Dictionary <string, int>();
                foreach (var referencedBlock in references)
                {
                    if (!nameIndexDict.ContainsKey(referencedBlock.Definition.Name))
                    {
                        var objs  = referencedBlock.Definition.GetObjects();
                        var geos  = new GeometryBase[objs.Length];
                        var attrs = new ObjectAttributes[objs.Length];
                        for (int i = 0; i < objs.Length; i++)
                        {
                            geos[i]  = objs[i].Geometry;
                            attrs[i] = objs[i].Attributes;
                        }

                        var index = doc.AllInstanceDefinitions.Add(referencedBlock.Definition.Name, nested.Definition.Description,
                                                                   Point3d.Origin, geos, attrs);
                        nameIndexDict.Add(referencedBlock.Definition.Name, index);
                    }

                    doc.Objects.AddInstanceObject(nameIndexDict[referencedBlock.Definition.Name],
                                                  referencedBlock.BlockInsertionParameters.InstanceXform);
                }
            }

            return(doc.Write(filePath, RhinoApp.ExeVersion));
        }
Esempio n. 5
0
        public static RhinoGeometryContainer ReadRhino(string path)
        {
            RhinoGeometryContainer geoContainer = new RhinoGeometryContainer();

            try
            {
                File3dm rhinoFile = File3dm.Read(path);
                geoContainer.FilePath = path;

                File3dmObjectTable objects = rhinoFile.Objects;
                foreach (File3dmObject fileObj in objects)
                {
                    Guid         objId    = fileObj.Attributes.ObjectId;
                    string       name     = fileObj.Name;
                    GeometryBase geometry = fileObj.Geometry;

                    RhinoObjectInfo objInfo = new RhinoObjectInfo(objId, name, geometry);

                    CollectGeometryInfo(objInfo, ref geoContainer);
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
            }
            return(geoContainer);
        }
Esempio n. 6
0
        private void makeBayView(File3dm file, StructuralBay bay)
        {
            //File3dm file = setupFile();
            RhinoViewport viewport = new RhinoViewport();

            //shift to mid point of module
            Point3d origin = new Point3d(bay.minPlane.Origin);
            Plane   plnA   = new Plane(origin + bay.minPlane.YAxis * bay.parameters.yCell / 2, bay.minPlane.XAxis, Vector3d.ZAxis);
            //shift to end of module
            Plane plnB = new Plane(origin + bay.minPlane.YAxis * bay.parameters.yCell, bay.minPlane.XAxis, Vector3d.ZAxis);

            plnA.Flip();


            viewport.SetProjection(DefinedViewportProjection.Perspective, "bay_" + bay.baynum.ToString() + "section", false);

            viewport.ChangeToParallelProjection(true);

            //set camera and target
            Vector3d shiftTarget = bay.maxPlane.Origin - bay.minPlane.Origin;

            viewport.SetCameraTarget(bay.minPlane.Origin + shiftTarget / 2, false);
            viewport.SetCameraLocation(viewport.CameraTarget + bay.minPlane.YAxis * -50000, false);
            viewport.SetCameraDirection(viewport.CameraTarget - viewport.CameraTarget, false);
            viewport.CameraUp = Vector3d.ZAxis;
            //viewport.ZoomExtents();
            viewport.PushViewProjection();
            file.AllViews.Add(new ViewInfo(viewport));

            //Clip plane A
            file.Objects.AddClippingPlane(plnA, bay.parameters.width, bay.parameters.height, viewport.Id);
            //Clip plane B
            file.Objects.AddClippingPlane(plnB, bay.parameters.width, bay.parameters.height, viewport.Id);
        }
        public static List <IEnumerable> GetAllTables(File3dm file)
        {
            List <Type>   memTypes;
            List <string> names;

            return(GetAllTables(file, out memTypes, out names));
        }
Esempio n. 8
0
        private static int getLayerIndex(ObjectLayerInfo li, File3dm f)
        {
            File3dmLayerTable layers = f.AllLayers;

            if (li.Name.Contains(Layer.PathSeparator))
            {
                foreach (Layer l in f.AllLayers)
                {
                    if (l.FullPath == li.Name)
                    {
                        return(l.Index);
                    }
                }
            }
            else
            {
                foreach (Layer l in f.AllLayers)
                {
                    if (l.Name == li.Name)
                    {
                        return(l.Index);
                    }
                }
            }

            return(-1);
        }
        private static FileState ParseFile(File3dm file, DataStore store, RvcVersion version, out ChangeSet changes)
        {
            FileState             state           = null;
            List <IFileDataTable> parsedTableList = new List <IFileDataTable>();
            //opening the store, and the file and comparing the contents
            List <Type>        memberTypes;
            List <string>      tableNames;
            List <IEnumerable> tables3dm   = GetAllTables(file, out memberTypes, out tableNames);
            ChangeSet          fileChanges = new ChangeSet();

            for (int i = 0; i < tables3dm.Count; i++)
            {
                ChangeSet      tableChanges;
                IFileDataTable parsedTable = TableUtil.ParseTableData(tables3dm[i], tableNames[i], memberTypes[i], version, store, out tableChanges);
                parsedTableList.Add(parsedTable);
                fileChanges = ChangeSet.Merge(fileChanges, tableChanges);
            }

            //populating the file state
            state = new FileState(store, version.AddDownStreamVersion(fileChanges));
            foreach (var table in parsedTableList)
            {
                state.Tables.Add(table);
            }
            changes = fileChanges;
            return(state);
        }
Esempio n. 10
0
        public static Brep Initialize(string file_name)
        {
            File3dm my_file = File3dm.Read(file_name, File3dm.TableTypeFilter.ObjectTable, File3dm.ObjectTypeFilter.Brep);

            File3dmObject[] my_obj  = my_file.Objects.FindByLayer("Default");
            int             count   = my_file.Objects.Count;
            Brep            my_brep = new Brep();

            for (int i = 0; i < count; i++)
            {
                if (my_obj[i].Geometry.HasBrepForm)
                {
                    RhinoApp.WriteLine("Has Brep form");
                    Brep my_brep_1 = Brep.TryConvertBrep(my_obj[i].Geometry);
                    if (my_brep_1.Surfaces.Count > 1)
                    {
                        my_brep = my_brep_1;
                        break;
                    }
                }
            }

            my_brep.UserDictionary.Set("Name", "DefaultName");
            my_brep.UserDictionary.Set("Category", "DefaultCategory");
            my_brep.UserDictionary.Set("Color", Color.Empty.Name);
            my_brep.UserDictionary.Set("ComponentID", Guid.NewGuid());
            my_brep.UserDictionary.Set("Position", new Point3d(0, 0, 0));
            my_brep.UserDictionary.Set("Z_Direction", new Vector3d(0, 0, 1));
            my_brep.UserDictionary.Set("Y_Direction", new Vector3d(0, 1, 0));
            my_brep.UserDictionary.Set("X_Direction", new Vector3d(1, 0, 0));
            my_brep.UserDictionary.Set("PinQuantity", 0);

            return(my_brep);
        }
        public void CombineRhinoFilesAsInstance(string folder, string outfilepath, string search, List <Brep> refgeo)
        {
            var files = Directory.GetFiles(folder, "*.3dm", SearchOption.TopDirectoryOnly);

            File3dm outfile = new File3dm();

            Layer layer = new Layer();

            layer.Name = "envelope";
            outfile.AllLayers.Add(layer);
            var transform = Transform.Identity;

            foreach (string s in files)
            {
                if (s.Contains(search))
                {
                    string reffile = Path.GetFileNameWithoutExtension(s);
                    int    index   = outfile.AllInstanceDefinitions.AddLinked(s, reffile, reffile);
                    InstanceDefinitionGeometry instance = outfile.AllInstanceDefinitions.FindName(s);
                    outfile.Objects.AddInstanceObject(index, transform);
                }
            }
            foreach (Brep b in refgeo)
            {
                ObjectAttributes att = new ObjectAttributes();
                att.LayerIndex = 0;
                outfile.Objects.AddBrep(b, att);
            }
            outfile.Write(folder + "\\" + outfilepath, 5);
        }
        public void CombineRhinoFilesAsGeo(string folder, string outfilepath, string search, List <Brep> refgeo)
        {
            var files = Directory.GetFiles(folder, "*.3dm", SearchOption.TopDirectoryOnly);

            File3dm outfile = new File3dm();

            Layer layer = new Layer();

            layer.Name = "envelope";
            outfile.AllLayers.Add(layer);
            var transform = Transform.Identity;

            foreach (string s in files)
            {
                if (s.Contains(search))
                {
                    File3dm read = File3dm.Read(s);

                    foreach (File3dmObject o in read.Objects)
                    {
                        outfile.Objects.Add(o);
                    }
                }
            }
            foreach (Brep b in refgeo)
            {
                ObjectAttributes att = new ObjectAttributes();
                att.LayerIndex = 0;
                outfile.Objects.AddBrep(b, att);
            }
            outfile.Write(folder + "\\" + outfilepath, 5);
        }
        public static FileState ParseFile(string filePath, out ChangeSet changes)
        {
            if (!IsValidRhinoFile(filePath))
            {
                changes = null;
                return(null);
            }
            //opening the store, and the file and comparing the contents
            using (var file = File3dm.Read(filePath))
            {
                string             tetherJson = file.Strings.GetValue(RvcRhinoFileTether.RvcTetherKey);
                string             dirPath    = Path.GetDirectoryName(filePath);
                RvcRhinoFileTether tether;
                RvcVersion         version = null;
                if (tetherJson == null)
                {
                    version = new RvcVersion();
                    tether  = new RvcRhinoFileTether(version.Id);
                }
                else
                {
                    tether  = JsonConvert.DeserializeObject <RvcRhinoFileTether>(tetherJson);
                    version = RvcVersion.ReadRootVersion(Path.Combine(dirPath, RvcRhinoFileTether.RvcArchiveDirectoryName, tether.RvcId.ToString()));
                }
                RvcArchive archive = new RvcArchive(tether, version, Path.GetDirectoryName(filePath));

                using (var store = new DataStore(filePath, tether.RvcId))
                {
                    return(ParseFile(file, store, version, out changes));
                }
            }
        }
 private void BTN_Convert_Click(object sender, EventArgs e)
 {
     var versionNumber = RhinoVersions[versionBox.SelectedIndex];
     var task          = Task.Run(() =>
     {
         foreach (var model in Models)
         {
             if (File.Exists(model))
             {
                 var _3dm        = File3dm.Read(model);
                 var finfo       = new FileInfo(model);
                 var dir         = finfo.Directory.FullName;
                 var newFileName = Path.Combine(dir, Path.GetFileNameWithoutExtension(model) + $"_VERSION{versionNumber}.3dm");
                 UpdateFilePathBoxText(model);
                 UpdateStatusText($"Status: Saving file as version {versionNumber} file.");
                 try
                 {
                     _3dm.Write(newFileName, versionNumber);
                     UpdateStatusText("Status: Saved file. Success.");
                     EnableConvertButton(false);
                 }
                 catch (Exception fileSaveError)
                 {
                     MessageBox.Show($"Error while trying to save new file! Message: {Environment.NewLine}{fileSaveError.Message}");
                     UpdateStatusText("Status: Failed to save file.");
                 }
             }
             else
             {
                 UpdateStatusText("Status: Could't find file path.");
             }
         }
     });
 }
Esempio n. 15
0
        private void Btn_OpenFile_OnClick(object sender, RoutedEventArgs e)
        {
            // create new open file dialog
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Filter = "Rhino files (*.3dm)|*.3dm|All files (*.*)|*.*"
            };

            openFileDialog.Multiselect = false;

            if (openFileDialog.ShowDialog() == true)
            {
                // Clear viewport
                Viewport.Children.Clear();

                // populate fields
                _filepath   = openFileDialog.FileName;
                _file       = RhinoFileReader.ReadFile(openFileDialog.FileName);
                _properties = new File3dmProperties(_file);
                _camera     = _properties.GetCamera();

                _properties.Name = _filepath.Split('\'').Last();

                lB_FileProperties.ItemsSource = _properties.ToList();
                Viewport.Camera = _camera;

                var modelVisual3d = new ModelVisual3D();
                var modelGroup    = new Model3DGroup();

                // Define the lights cast in the scene. Without light, the 3D object cannot
                // be seen. Note: to illuminate an object from additional directions, create
                // additional lights.
                //DirectionalLight myDirectionalLight = new DirectionalLight();
                //myDirectionalLight.Color = Colors.White;
                //myDirectionalLight.Direction = new Vector3D(-0.61, -0.5, -0.61);

                //modelGroup.Children.Add(myDirectionalLight);

                // Add ambient light
                //AmbientLight myAmbientLight = new AmbientLight(Colors.White);
                //modelGroup.Children.Add(myAmbientLight);

                // Add lights
                foreach (var light in _properties.Lights)
                {
                    modelGroup.Children.Add(light);
                }

                // Add render meshes
                foreach (var propertiesRenderMesh in _properties.RenderMeshes)
                {
                    modelGroup.Children.Add(propertiesRenderMesh);
                }

                modelVisual3d.Content = modelGroup;
                Viewport.Children.Add(modelVisual3d);
            }
        }
Esempio n. 16
0
        static IList <GeometryObject> ImportObject(File3dm model, GeometryBase geometry, ObjectAttributes attributes, Document doc, Dictionary <string, Autodesk.Revit.DB.Material> materials, double scaleFactor)
        {
            var layer = model.AllLayers.FindIndex(attributes.LayerIndex);

            if (layer?.IsVisible ?? false)
            {
                using (var ctx = Convert.Context.Push())
                {
                    switch (attributes.MaterialSource)
                    {
                    case ObjectMaterialSource.MaterialFromObject:
                    {
                        var modelMaterial = attributes.MaterialIndex < 0 ? Rhino.DocObjects.Material.DefaultMaterial : model.AllMaterials.FindIndex(attributes.MaterialIndex);
                        ctx.MaterialId = ToHost(modelMaterial, doc, materials);
                        break;
                    }

                    case ObjectMaterialSource.MaterialFromLayer:
                    {
                        var modelLayer    = model.AllLayers.FindIndex(attributes.LayerIndex);
                        var modelMaterial = modelLayer.RenderMaterialIndex < 0 ? Rhino.DocObjects.Material.DefaultMaterial : model.AllMaterials.FindIndex(modelLayer.RenderMaterialIndex);
                        ctx.MaterialId = ToHost(modelMaterial, doc, materials);
                        break;
                    }
                    }

                    if (geometry is InstanceReferenceGeometry instance)
                    {
                        if (model.AllInstanceDefinitions.FindId(instance.ParentIdefId) is InstanceDefinitionGeometry definition)
                        {
                            var definitionId = definition.Id.ToString();
                            var library      = DirectShapeLibrary.GetDirectShapeLibrary(doc);
                            if (!library.Contains(definitionId))
                            {
                                var objectIds = definition.GetObjectIds();
                                var GNodes    = objectIds.
                                                Select(x => model.Objects.FindId(x)).
                                                Cast <File3dmObject>().
                                                SelectMany(x => ImportObject(model, x.Geometry, x.Attributes, doc, materials, scaleFactor));

                                library.AddDefinition(definitionId, GNodes.ToArray());
                            }

                            var xform = instance.Xform.ChangeUnits(scaleFactor);
                            return(DirectShape.CreateGeometryInstance(doc, definitionId, xform.ToHost()));
                        }
                    }
                    else
                    {
                        return(geometry.ToHostMultiple(scaleFactor).ToList());
                    }
                }
            }

            return(new GeometryObject[0]);
        }
Esempio n. 17
0
        public _OdDb.ObjectIdCollection BakeGhGeometry(IGH_StructureEnumerator se)
        {
            var tmpFile = new File3dm();

            foreach (var paramValue in se)
            {
                AddGeometry(tmpFile, paramValue);
            }
            return(BakeGhGeometry(tmpFile));
        }
Esempio n. 18
0
        public bool readfile(string layername)
        {
            string my_path = "D:/Desktop/assembly.3dm";

            RhinoApp.WriteLine(my_path);
            try
            {
                RhinoApp.WriteLine("start trying");
                //RhinoApp.WriteLine("the number of objects is {0}", my_file.Objects.Count);
                my_file = File3dm.Read(my_path, File3dm.TableTypeFilter.ObjectTable, File3dm.ObjectTypeFilter.Any);
                //System.Threading.Thread.Sleep(500);
                //string error;
                //my_file.IsValid(out error);
                //RhinoApp.WriteLine("error is {0}", error);
                RhinoApp.WriteLine("the number of objects is {0}", my_file.Objects.Count);
                RhinoApp.WriteLine("the objects is {0}", my_file.Objects.ToString());

                //GeometryBase my_geometry = my_file.Objects[0].Geometry.Duplicate();
                //RhinoApp.WriteLine("name {0}", my_file.Objects[0].Name);
                //uint number = 0;
                File3dmObject[] my_obj = my_file.Objects.FindByLayer("Default");
                RhinoApp.WriteLine("after read");
                //RhinoApp.WriteLine("after read geometry");
                int count = my_file.Objects.Count;
                for (int i = 0; i < count; i++)
                {
                    if (my_obj[i].Geometry.HasBrepForm)
                    {
                        RhinoApp.WriteLine("Has Brep form");
                        Brep my_brep_1 = Brep.TryConvertBrep(my_obj[i].Geometry);
                        if (my_brep_1.Surfaces.Count > 1)
                        {
                            my_brep = my_brep_1;
                            break;
                        }
                    }
                }
                adduserdata();
                if_got_brep = true;
                //doc.Objects.AddBrep(my_brep);
                //doc.Views.Redraw();
                RhinoApp.WriteLine("Successfully setup the object");
                return(true);
            }
            catch (FileNotFoundException e)
            {
                RhinoApp.WriteLine("No Right Path");
                return(false);
            }
            catch (IndexOutOfRangeException e)
            {
                RhinoApp.WriteLine("No Object In This 3dm File");
                return(false);
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Gets Rhino layer names.
        /// </summary>
        /// <param name="RhinoModel">The Rhino model object</param>
        /// <returns name="LayerNames">List of Rhino layer names.</returns>
        /// <search>case,rhino,model,layers,3dm,rhynamo</search>
        public static List <string> Get_RhinoLayerNames(File3dm RhinoModel)
        {
            List <string> m_names = new List <string>();

            foreach (Rhino.DocObjects.Layer lay in RhinoModel.AllLayers)
            {
                m_names.Add(lay.Name);
            }
            // return info
            return(m_names);
        }
        public File3dmProperties(File3dm file3dm)
        {
            File3dm = file3dm;
            CreateRenderMeshes();
            CreateLights();

            Name = File3dm.CreatedBy;

            LayerCount           = File3dm.AllLayers.Count;
            ObjectCount          = File3dm.Objects.Count;
            BlockDefinitionCount = File3dm.AllInstanceDefinitions.Count;
        }
Esempio n. 21
0
        public static Result Import3DMFile(string filePath, Document doc, BuiltInCategory builtInCategory)
        {
            using (var model = File3dm.Read(filePath))
            {
                var scaleFactor = RhinoMath.UnitScale(model.Settings.ModelUnitSystem, Revit.ModelUnitSystem);

                using (var trans = new Transaction(doc, "Import 3D Model"))
                {
                    if (trans.Start() == TransactionStatus.Started)
                    {
                        var categoryId = new ElementId(builtInCategory);

                        var ds = DirectShape.CreateElement(doc, categoryId);
                        ds.Name = Path.GetFileName(filePath);

                        foreach (var obj in model.Objects)
                        {
                            if (!obj.Attributes.Visible)
                            {
                                continue;
                            }

                            var layer = model.AllLayers.FindIndex(obj.Attributes.LayerIndex);
                            if (layer?.IsVisible != true)
                            {
                                continue;
                            }

                            var geometryList = ImportObject(obj.Geometry, obj.Attributes, scaleFactor);
                            if (geometryList == null)
                            {
                                continue;
                            }

                            try { ds.AppendShape(geometryList); }
                            catch (Autodesk.Revit.Exceptions.ArgumentException) { }
                        }

                        if (trans.Commit() == TransactionStatus.Committed)
                        {
                            var elements = new ElementId[] { ds.Id };
                            Revit.ActiveUIDocument.Selection.SetElementIds(elements);
                            Revit.ActiveUIDocument.ShowElements(elements);

                            return(Result.Succeeded);
                        }
                    }
                }
            }

            return(Result.Failed);
        }
Esempio n. 22
0
 private void addCurves(File3dm file, List <Curve> curves, Plane p, ObjectAttributes att, Vector3d t)
 {
     foreach (Curve c in curves)
     {
         if (curveInHalfSpace(c, p))
         {
             var pts = mapAndTranslatePts(p, new List <Point3d> {
                 c.PointAtStart, c.PointAtEnd
             }, t);
             file.Objects.AddLine(new Line(pts[0], pts[1]), att);
         }
     }
 }
        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine(@"Usage: dotnet run hello_mesh.3dm");
                return;
            }

            var path = args[0];
            var doc  = File3dm.Read(path);

            Console.WriteLine($"{path} has {doc.Objects.Count} objects!");
        }
Esempio n. 24
0
        internal InstanceDefinitionGeometry(Guid id, File3dm parent)
            : base()
        {
            m_id      = id;
            m__parent = parent;

            // 20 Nov 2018 S. Baer (RH-49605)
            // Instance definition geometry that is a child of a File3dm should not hold
            // onto it's pointer.
            //IntPtr parent_ptr = parent.ConstPointer();
            //IntPtr idf_ptr = UnsafeNativeMethods.ONX_Model_GetModelComponentPointer(parent_ptr, id);

            //ConstructNonConstObject(idf_ptr);
        }
Esempio n. 25
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            var dialog = new OpenFileDialog
            {
                Filter     = @"Rhino 3D Models (*.3dm)|*.3dm",
                DefaultExt = "3dm"
            };

            var rc = dialog.ShowDialog();

            if (rc != DialogResult.OK)
            {
                return(Result.Cancel);
            }

            var filename = dialog.FileName;

            if (string.IsNullOrEmpty(filename) || !File.Exists(filename))
            {
                return(Result.Failure);
            }

            var file = File3dm.Read(filename);

            if (null == file)
            {
                return(Result.Failure);
            }

            // Layers do not store their full path name. Full layer path names are generated,
            // as needed, by a function the document's layer table. Basically, the function
            // check to see if the layer has a parent and, if so, prepends the parent's name
            // to the layer name. And then the parent layer check to see if it has a parent,
            // etc., until no parent is found.

            // The layer's collection in File3dm is just an ignorant collection. So if you want
            // to generate full layer path names from layers in in File3dm, you need to write your
            // own function.

            for (var i = 0; i < file.AllLayers.Count; i++)
            {
                string full_name = null;
                if (GetLayerPathName(file, i, ref full_name))
                {
                    RhinoApp.WriteLine(full_name);
                }
            }

            return(Result.Success);
        }
Esempio n. 26
0
 /// <summary>
 /// Search for a layer with a matching id.
 /// </summary>
 private int FindLayerFromId(File3dm file, Guid id)
 {
     if (null != file && id != Guid.Empty)
     {
         for (var i = 0; i < file.AllLayers.Count; i++)
         {
             if (file.AllLayers.FindIndex(i).Id == id)
             {
                 return(i);
             }
         }
     }
     return(-1);
 }
Esempio n. 27
0
        /// <summary>
        /// The RhinoHead function.
        /// </summary>
        /// <param name="model">The input model.</param>
        /// <param name="input">The arguments to the execution.</param>
        /// <returns>A RhinoHeadOutputs instance containing computed results and the model with any new elements.</returns>
        public static RhinoHeadOutputs Execute(Dictionary <string, Model> inputModels, RhinoHeadInputs input)
        {
            var doc = File3dm.Read("hello_mesh.3dm");
            //var doc = File3dm.Read("/home/ec2-user/hypar_test/StarterFunction/models/hello_mesh.3dm");

            var meshes = new List <MeshElement>();

            foreach (var obj in doc.Objects)
            {
                if (!(obj.Geometry is Rhino.Geometry.Mesh m))
                {
                    continue;
                }

                m.Compact(); // remove any unreferenced vertices

                var mesh = new Mesh();

                foreach (var v in m.Vertices)
                {
                    var x = (double)v.X;
                    var y = (double)v.Y;
                    var z = (double)v.Z;
                    mesh.AddVertex(new Vector3(x, y, z));
                }

                foreach (var f in m.Faces)
                {
                    if (f.IsTriangle)
                    {
                        mesh.AddTriangle(mesh.Vertices[f.A], mesh.Vertices[f.B], mesh.Vertices[f.C]);
                    }
                    else
                    {
                        mesh.AddTriangle(mesh.Vertices[f.A], mesh.Vertices[f.B], mesh.Vertices[f.C]);
                        mesh.AddTriangle(mesh.Vertices[f.C], mesh.Vertices[f.D], mesh.Vertices[f.A]);
                    }
                }

                mesh.ComputeNormals();
                var shiny = new Material("shiny", Colors.Red, 1.0, 0.9);
                meshes.Add(new MeshElement(mesh, shiny));
            }

            var output = new RhinoHeadOutputs((double)doc.Objects.Count);

            output.Model.AddElements(meshes);
            return(output);
        }
Esempio n. 28
0
        public static List <MedinaSiteSector> LoadSite(string path)
        {
            var file = File3dm.Read(path);

            Console.WriteLine($"Reading {path.Split('\\').Last().Replace(".3dm", "")} with {file.Objects.Count.ToString()} objects...");

            var sectors = new List <MedinaSiteSector>();

            //Read all objects and group by sector.
            var objectDictionary = new Dictionary <string, List <File3dmObject> >();

            foreach (var obj in file.Objects)
            {
                if (obj.Name != null)
                {
                    objectDictionary.TryGetValue(obj.Name, out var res);

                    if (res != null)
                    {
                        //Add object.
                        objectDictionary[obj.Name].Add(obj);
                    }
                    else
                    {
                        //Initialize object list.
                        objectDictionary[obj.Name] = new List <File3dmObject>();
                        objectDictionary[obj.Name].Add(obj);
                    }

                    //Console.WriteLine($@"{file.AllLayers.FindIndex(obj.Attributes.LayerIndex).Name} object @ {obj.Name}");
                }
            }

            foreach (var key in objectDictionary.Keys.Select(x => x.ToString()))
            {
                var builder = new MedinaSiteSectorBuilder();

                var sector = builder.CreateSector(file)
                             .WithId(key)
                             .WithObjects(objectDictionary[key])
                             .CategorizeObjects();

                sectors.Add(sector);
            }

            return(sectors);
        }
Esempio n. 29
0
        private void writeRhino3dm(File3dm f, string filePath, List <ObjectLayerInfo> G, List <int> att)
        {
            for (int i = 0; i < G.Count; i++)
            {
                GeometryBase     g    = GH_Convert.ToGeometryBase(G[i].Geometry);
                ObjectAttributes attr = new ObjectAttributes();
                attr.LayerIndex = att[i];

                if (g != null)
                {
                    switch (g.ObjectType)
                    {
                    case ObjectType.Brep:
                        f.Objects.AddBrep(g as Brep, attr);
                        break;

                    case ObjectType.Curve:
                        f.Objects.AddCurve(g as Curve, attr);
                        break;

                    case ObjectType.Point:
                        f.Objects.AddPoint((g as Rhino.Geometry.Point).Location, attr);
                        break;

                    case ObjectType.Surface:
                        f.Objects.AddSurface(g as Surface, attr);
                        break;

                    case ObjectType.Mesh:
                        f.Objects.AddMesh(g as Mesh, attr);
                        break;

                    case ObjectType.PointSet:
                        f.Objects.AddPointCloud(g as PointCloud, attr);     //This is a speculative entry
                        break;

                    default:
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "不能识别的物体: " + G.GetType().FullName);
                        break;
                    }
                }
            }

            f.Write(filePath, 5);
            f.Dispose();
        }
Esempio n. 30
0
        static DB.ElementId ImportLayer
        (
            DB.Document doc,
            File3dm model,
            Layer layer,
            Dictionary <string, DB.Category> categories,
            Dictionary <string, DB.Material> materials
        )
        {
            var id = DB.ElementId.InvalidElementId;

            if (layer.HasName)
            {
                var matName = layer.Name;
                if (categories.TryGetValue(matName, out var category))
                {
                    id = category.Id;
                }
                else
                {
                    var familyCategory = doc.OwnerFamily.FamilyCategory;
                    if (familyCategory.CanAddSubcategory)
                    {
                        if (doc.Settings.Categories.NewSubcategory(familyCategory, layer.Name) is DB.Category subCategory)
                        {
                            subCategory.LineColor = layer.Color.ToColor();

                            var modelMaterial = layer.RenderMaterialIndex >= 0 ? model.AllMaterials.FindIndex(layer.RenderMaterialIndex) : default;
                            if (modelMaterial is object)
                            {
                                if (doc.GetElement(ImportMaterial(doc, modelMaterial, materials)) is DB.Material material)
                                {
                                    subCategory.Material = material;
                                }
                            }

                            categories.Add(subCategory.Name, subCategory);
                            id = subCategory.Id;
                        }
                    }
                }
            }

            return(id);
        }
    internal void SetParent(File3dm parent)
    {
      if (m_parent != parent)
      {
        m_notes = Notes;
        m_visible = IsVisible;
        m_html = IsHtml;
        m_winrect = WindowRectangle;

        m_parent = parent;
        if (parent != null)
        {
          Notes = m_notes;
          IsVisible = m_visible;
          IsHtml = m_html;
          WindowRectangle = m_winrect;
        }
      }
    }
 internal File3dmNotes(File3dm parent)
 {
   m_parent = parent;
 }
 internal File3dmSettings(File3dm parent)
 {
   m_parent = parent;
 }