Beispiel #1
0
        /***************************************************/
        /**** Private Methods                            ****/
        /***************************************************/

        private static IBHoMObject _ShallowClone(this IBHoMObject bhomObject, bool newGuid = false)
        {
            IBHoMObject clone = DeepClonerExtensions.ShallowClone(bhomObject);

            if (bhomObject.CustomData != null)
            {
                clone.CustomData = new Dictionary <string, object>(bhomObject.CustomData);
            }
            else
            {
                clone.CustomData = new Dictionary <string, object>();
            }

            if (bhomObject.Tags != null)
            {
                clone.Tags = new HashSet <string>(bhomObject.Tags);
            }
            else
            {
                clone.Tags = new HashSet <string>();
            }

            if (newGuid)
            {
                clone.BHoM_Guid = Guid.NewGuid();
            }

            return(clone);
        }
        public static IBHoMObject AddFragment(this IBHoMObject iBHoMObject, IBHoMFragment fragment, bool replace = false)
        {
            if (iBHoMObject == null)
            {
                return(null);
            }
            IBHoMObject o = iBHoMObject.DeepClone();

            int index = o.Fragments.FindIndex(x => x.GetType() == fragment.GetType());

            if (index >= 0)
            {
                if (replace)
                {
                    o.Fragments[index] = fragment;
                }
                else
                {
                    Reflection.Compute.RecordError("That fragment already exists on this object. If you would like to replace the existing fragment set the 'replace' input to 'true'");
                }
            }
            else
            {
                o.Fragments.Add(fragment);
            }

            return(o);
        }
Beispiel #3
0
        private static string GetIdFromFragment(this IBHoMObject obj, Type fragmentType, string fragmentIdProperty)
        {
            if (!typeof(IFragment).IsAssignableFrom(fragmentType))
            {
                BH.Engine.Reflection.Compute.RecordError("The specified Type must be a fragment Type.");
                return(null);
            }

            // Check on fragmentIdProperty
            if (string.IsNullOrWhiteSpace(fragmentIdProperty))
            {
                BH.Engine.Reflection.Compute.RecordError($"Invalid {nameof(fragmentIdProperty)} provided.");
                return(null);
            }

            IFragment idFragm = obj.FindFragment <IFragment>(fragmentType);

            if (idFragm == null)
            {
                BH.Engine.Reflection.Compute.RecordWarning($"Object of type {obj.GetType()}, guid {obj.BHoM_Guid} does not contain a fragment of the provided Fragment type {fragmentType}.");
                return(null);
            }

            object value = BH.Engine.Reflection.Query.PropertyValue(idFragm, fragmentIdProperty);

            if (value == null)
            {
                BH.Engine.Reflection.Compute.RecordWarning($"The retrieved fragment for an object of type {obj.GetType()}, guid {obj.BHoM_Guid} has not any value under the property named {fragmentIdProperty}.");
                return(null);
            }

            return(value.ToString());
        }
Beispiel #4
0
        /***************************************************/

        public static Element Create(IBHoMObject bHoMObject, Document document, RevitSettings settings, Dictionary <Guid, List <int> > refObjects)
        {
            if (bHoMObject == null)
            {
                NullObjectCreateError(typeof(IBHoMObject));
                return(null);
            }

            try
            {
                Element element = bHoMObject.IToRevit(document, settings, refObjects);
                bHoMObject.SetIdentifiers(element);

                //Assign Tags
                string tagsParameterName = null;
                if (settings != null)
                {
                    tagsParameterName = settings.ParameterSettings?.TagsParameter;
                }

                if (!string.IsNullOrEmpty(tagsParameterName))
                {
                    element.SetTags(bHoMObject, tagsParameterName);
                }

                return(element);
            }
            catch (Exception ex)
            {
                ObjectNotCreatedError(bHoMObject, ex);
                return(null);
            }
        }
        /***************************************************/
        /****               Public Methods              ****/
        /***************************************************/

        public static bool Update(this Element element, IBHoMObject bHoMObject, RevitSettings settings, bool setLocationOnUpdate)
        {
            bool isElement = new ElementIsElementTypeFilter(true).PassesFilter(element);

            if (isElement)
            {
                if (element.ISetType(bHoMObject, settings))
                {
                    element.Document.Regenerate();
                }
            }

            element.CopyParameters(bHoMObject, settings);

            if (!string.IsNullOrWhiteSpace(bHoMObject.Name) && element.Name != bHoMObject.Name)
            {
                try
                {
                    element.Name = bHoMObject.Name;
                }
                catch
                {
                }
            }

            if (setLocationOnUpdate && isElement)
            {
                element.ISetLocation(bHoMObject, settings);
            }

            return(true);
        }
        // Fallback
        private static IGeometry GeometricalRepresentation(this IObject obj, RepresentationOptions reprOptions = null)
        {
            IGeometry geometricalRepresentation = null;

            // - Check if the object is a IGeometry, and if it is return itself.
            geometricalRepresentation = obj as IGeometry;
            if (geometricalRepresentation != null)
            {
                return(geometricalRepresentation);
            }

            // - If not, check if the object is a IBHoMObject whose IGeometry can be returned.
            IBHoMObject bHoMObject = obj as IBHoMObject;

            if (bHoMObject != null)
            {
                geometricalRepresentation = BH.Engine.Base.Query.IGeometry(bHoMObject);
            }

            // - Empty CompositeGeometries must not be considered valid.
            if (geometricalRepresentation != null)
            {
                if (geometricalRepresentation is CompositeGeometry && (geometricalRepresentation as CompositeGeometry).Elements.Count < 1)
                {
                    geometricalRepresentation = null;
                }
            }

            return(geometricalRepresentation);
        }
Beispiel #7
0
        public static IBHoMObject AddFragment(this IBHoMObject iBHoMObject, IBHoMFragment fragment, bool replace = false)
        {
            if (iBHoMObject == null)
            {
                return(null);
            }
            IBHoMObject o = iBHoMObject.DeepClone();

            o.Fragments = new List <IBHoMFragment>(iBHoMObject.Fragments);
            if (o.Fragments.Contains(fragment))
            {
                if (replace)
                {
                    o.Fragments[o.Fragments.IndexOf(fragment)] = fragment;
                }
                else
                {
                    Reflection.Compute.RecordError("That fragment already exists on this object. If you would like to replace the existing fragment set the 'replace' input to 'true'");
                }
            }
            else
            {
                o.Fragments.Add(fragment);
            }

            return(o);
        }
Beispiel #8
0
        public static ClonedType CloneType(this IBHoMObject sourceRevitObject, string newName)
        {
            if (sourceRevitObject == null)
            {
                BH.Engine.Reflection.Compute.RecordError("It is impossible to clone a null Revit object.");
                return null;
            }

            RevitIdentifiers identifiers = sourceRevitObject.FindFragment<RevitIdentifiers>();
            if (identifiers == null)
            {
                BH.Engine.Reflection.Compute.RecordError("The input object is not a valid pulled Revit element.");
                return null;
            }

            ClonedType result = new ClonedType { SourceTypeId = identifiers.FamilyTypeId, Name = newName };
            if (identifiers.ElementId == identifiers.FamilyTypeId)
            {
                RevitParametersToPush parametersToPush = sourceRevitObject.FindFragment<RevitParametersToPush>();
                if (parametersToPush != null)
                {
                    BH.Engine.Reflection.Compute.RecordWarning("Parameters to push have been cloned from the source Revit type object.");
                    result.AddFragment(parametersToPush.DeepClone());
                }
            }
            else
                BH.Engine.Reflection.Compute.RecordWarning("The input object is a pulled Revit element, its type has been cloned.");

            return result;
        }
Beispiel #9
0
        public static Graph UniqueEntities(this Graph graph, Dictionary <Guid, IBHoMObject> replaceMap)
        {
            Dictionary <Guid, IBHoMObject> uniqueEntities = new Dictionary <Guid, IBHoMObject>();

            foreach (KeyValuePair <Guid, IBHoMObject> kvp in graph.Entities)
            {
                IBHoMObject unique = replaceMap[kvp.Key];
                if (!uniqueEntities.ContainsKey(unique.BHoM_Guid))
                {
                    uniqueEntities.Add(unique.BHoM_Guid, unique);
                }
            }

            graph.Entities = uniqueEntities;

            List <IRelation> uniqueRelations = new List <IRelation>();

            foreach (IRelation relation in graph.Relations)
            {
                IRelation relation1 = relation.UniqueEntities(replaceMap);

                //keep if it does not already exist
                if (!uniqueRelations.Any(r => r.Source.Equals(relation1.Source) && r.Target.Equals(relation1.Target)))
                {
                    uniqueRelations.Add(relation1);
                }
            }
            graph.Relations = uniqueRelations;
            return(graph);
        }
Beispiel #10
0
        /***************************************************/
        /****              Public methods               ****/
        /***************************************************/

        public static void SetIdentifiers(this IBHoMObject bHoMObject, Element element)
        {
            if (bHoMObject != null && element != null)
            {
                bHoMObject.Fragments.AddOrReplace(element.IIdentifiers());
            }
        }
Beispiel #11
0
        private static IBHoMObject SetRendermesh(this IBHoMObject bHoMObject, List <Mesh> representation)
        {
            Mesh       m  = Compute.JoinMeshes(representation);
            RenderMesh rm = m.ToRenderMesh();

            return(bHoMObject.SetRendermesh(m));
        }
Beispiel #12
0
        public static IBHoMObject RemoveFragment(this IBHoMObject iBHoMObject, Type fragmentType = null)
        {
            if (fragmentType == null)
            {
                return(iBHoMObject);
            }
            if (iBHoMObject == null)
            {
                return(null);
            }
            IBHoMObject o = iBHoMObject.DeepClone();

            if (!typeof(IFragment).IsAssignableFrom(fragmentType))
            {
                Reflection.Compute.RecordError("Provided input in fragmentType is not a Fragment type (does not implement IFragment interface).");
                return(iBHoMObject);
            }

            if (!iBHoMObject.Fragments.Contains(fragmentType))
            {
                Reflection.Compute.RecordWarning($"{iBHoMObject.GetType().Name} does not contain any `{fragmentType.Name}` fragment.");
                return(iBHoMObject);
            }

            o.Fragments.Remove(fragmentType);

            return(o);
        }
Beispiel #13
0
        /***************************************************/
        /**** Private Methods                           ****/
        /***************************************************/

        private static void SetEntityRepresentation(this IBHoMObject obj, int seqNumber, Boxes component, double xSpace, double ySpace)
        {
            double x     = 0;
            double y     = 0;
            double cellX = xSpace - 2 * component.Padding;
            double cellY = ySpace - 2 * component.Padding;

            if (component.IsHorizontal)
            {
                x = System.Convert.ToDouble(m_Xscale.IScale(seqNumber));
                y = System.Convert.ToDouble(m_Yscale.IScale(obj.PropertyValue(component.Group)));
            }
            else
            {
                x = System.Convert.ToDouble(m_Xscale.IScale(obj.PropertyValue(component.Group)));
                y = System.Convert.ToDouble(m_Yscale.IScale(seqNumber));
            }

            EntityRepresentation representation = new EntityRepresentation();

            Point basePt = SetAnchorPoint(Geometry.Create.Point(x, y, 0), component.Padding, component.Padding, 0);

            representation.Boundary              = Box(basePt, cellX, cellY);
            representation.Text                  = obj.PropertyValue(component.Text).ToString();
            representation.TextPosition          = SetAnchorPoint(basePt, component.Padding, component.Padding, 0);
            representation.OutgoingRelationPoint = SetAnchorPoint(basePt, cellX, cellY / 2, 0);
            representation.IncomingRelationPoint = SetAnchorPoint(basePt, 0, cellY / 2, 0);
            representation.Colour                = Convert.ColourFromObject(m_Colourscale.IScale(obj.PropertyValue(component.Colour)));
            obj.Fragments.AddOrReplace(representation);
        }
Beispiel #14
0
        public static string DiffingHash(this object obj, DiffConfig diffConfig = null)
        {
            diffConfig = diffConfig == null ? new DiffConfig() : (DiffConfig)diffConfig.DeepClone();

            // The following is to consider only the PropertiesToInclude specified in the diffConfig.
            // Since the SHA hash algorithm can only consider "exceptions", we need to retrieve all the top level properties,
            // intersect them with the set of PropertiesToInclude, and treat all the properties that remain out as "exceptions" (not to be considered).
            if (diffConfig.PropertiesToConsider.Any())
            {
                IEnumerable <string> exceptions = BH.Engine.Reflection.Query.PropertyNames(obj).Except(diffConfig.PropertiesToConsider);
                diffConfig.PropertiesToIgnore.AddRange(exceptions);
            }

            // The current Hash must not be considered when computing the hash. Remove HashFragment if present.
            IBHoMObject bhomobj = obj as IBHoMObject;

            if (bhomobj != null)
            {
                bhomobj = BH.Engine.Base.Query.DeepClone(obj) as IBHoMObject;
                bhomobj.Fragments.Remove(typeof(HashFragment));
                return(Compute.SHA256Hash(bhomobj, diffConfig.PropertiesToIgnore));
            }

            return(Compute.SHA256Hash(obj, diffConfig.PropertiesToIgnore));
        }
Beispiel #15
0
        /***************************************************/

        public static void SetTags(this IBHoMObject bHoMObject, Element element, string tagsParameterName)
        {
            if (bHoMObject == null || element == null || string.IsNullOrEmpty(tagsParameterName))
            {
                return;
            }

            Parameter parameter = element.LookupParameter(tagsParameterName);

            if (parameter == null || parameter.StorageType != StorageType.String)
            {
                return;
            }

            string tags = parameter.AsString();

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

            if (bHoMObject.Tags == null)
            {
                bHoMObject.Tags = new System.Collections.Generic.HashSet <string>();
            }

            string[] values = tags.Split(new string[] { "; " }, StringSplitOptions.None);

            foreach (string value in values)
            {
                bHoMObject.Tags.Add(value);
            }
        }
Beispiel #16
0
        /***************************************************/
        private static List <IBHoMObject> RandomNeighbours(List <List <List <IBHoMObject> > > entities, int i, int j, int k)
        {
            //from Von Neumann neighborhood randomly select 2 to all neighbours
            List <IBHoMObject> neighbours = new List <IBHoMObject>();
            int left    = i - 1;
            int right   = i + 1;
            int infront = j + 1;
            int behind  = j - 1;
            int below   = k - 1;
            int above   = k + 1;

            if (left >= 0)
            {
                neighbours.Add(entities[k][left][j]);
            }

            if (right <= entities[0].Count - 1)
            {
                neighbours.Add(entities[k][right][j]);
            }

            if (behind >= 0)
            {
                neighbours.Add(entities[k][i][behind]);
            }

            if (infront <= entities[0][0].Count - 1)
            {
                neighbours.Add(entities[k][i][infront]);
            }

            if (below >= 0)
            {
                neighbours.Add(entities[below][i][j]);
            }

            if (above <= entities.Count - 1)
            {
                neighbours.Add(entities[above][i][j]);
            }

            if (neighbours.Count <= 2)
            {
                return(neighbours);
            }

            int total = m_Rnd.Next(2, neighbours.Count);
            List <IBHoMObject> wanted = new List <IBHoMObject>();

            while (wanted.Count < total)
            {
                IBHoMObject next = neighbours[m_Rnd.Next(0, neighbours.Count)];
                if (wanted.Contains(next))
                {
                    continue;
                }
                wanted.Add(next);
            }
            return(wanted);
        }
Beispiel #17
0
        /***************************************************/
        /****              Public methods               ****/
        /***************************************************/

        public static void SetTags(this Element element, IBHoMObject bHoMObject, string tagsParameterName)
        {
            if (bHoMObject == null || element == null || string.IsNullOrEmpty(tagsParameterName))
            {
                return;
            }

            Parameter parameter = element.LookupParameter(tagsParameterName);

            if (parameter == null || parameter.IsReadOnly || parameter.StorageType != StorageType.String)
            {
                return;
            }

            string newValue = null;

            if (bHoMObject.Tags != null && bHoMObject.Tags.Count != 0)
            {
                newValue = string.Join("; ", bHoMObject.Tags);
            }

            string oldValue = parameter.AsString();

            if (newValue != oldValue)
            {
                parameter.Set(newValue);
            }
        }
Beispiel #18
0
        public static object PropertyValue(this object obj, string propName)
        {
            if (obj == null || propName == null)
            {
                return(null);
            }

            if (propName.Contains("."))
            {
                string[] props = propName.Split('.');
                foreach (string innerProp in props)
                {
                    obj = obj.PropertyValue(innerProp);
                    if (obj == null)
                    {
                        break;
                    }
                }
                return(obj);
            }

            System.Reflection.PropertyInfo prop = obj.GetType().GetProperty(propName);

            if (prop != null)
            {
                return(prop.GetValue(obj));
            }
            else if (obj is IBHoMObject)
            {
                IBHoMObject bhom = obj as IBHoMObject;
                if (bhom.CustomData.ContainsKey(propName))
                {
                    Compute.RecordNote($"{propName} is stored in CustomData");
                    return(bhom.CustomData[propName]);
                }
                else
                {
                    Compute.RecordWarning($"{bhom} does not contain a property: {propName}, or: CustomData[{propName}]");
                    return(null);
                }
            }
            else if (obj is IDictionary)
            {
                IDictionary dic = obj as IDictionary;
                if (dic.Contains(propName))
                {
                    return(dic[propName]);
                }
                else
                {
                    Compute.RecordWarning($"{dic} does not contain the key: {propName}");
                    return(null);
                }
            }
            else
            {
                Compute.RecordWarning($"This instance of {obj.GetType()} does not contain the property: {propName}");
                return(null);
            }
        }
Beispiel #19
0
        protected SpeckleObject ToSpeckle(IBHoMObject bhomObject, SpecklePushConfig config)
        {
            // Assign SpeckleStreamId to the Fragments of the IBHoMObjects
            SetAdapterId(bhomObject, SpeckleClient.Stream.StreamId);

            // SpeckleObject "container". Top level has geometry representation of BHoM Object, so it can be visualised in the SpeckleViewer.
            SpeckleObject speckleObject = SpeckleRepresentation(bhomObject, config.RendermeshOptions);

            // If no Speckle representation is found, it will be sent as an "Abstract" SpeckleObject (no visualisation).
            if (speckleObject == null)
            {
                speckleObject = (SpeckleObject)SpeckleCore.Converter.Serialise(bhomObject);
            }

            // Save BHoMObject data inside the speckleObject.
            Modify.SetBHoMData(speckleObject, bhomObject, config.UseSpeckleSerialiser);

            speckleObject.SetDiffingHash(bhomObject, config);

            // If the BHoMObject has a "RevisionName" string field in the Customdata,
            // use that value to create a Layer for it, and set the SpeckleObject's layer.
            //object revisionValue = null;
            //string revisionName = "";
            //if (bhomObject.CustomData.TryGetValue("RevisionName", out revisionValue))
            //{
            //    revisionName = revisionValue as string;
            //    if (!string.IsNullOrWhiteSpace(revisionName))
            //        speckleObject.Properties["revisionName"] = revisionName;
            //}

            return(speckleObject);
        }
        /***************************************************/

        internal static void CheckIfNullPush(this Element element, IBHoMObject bhomObject)
        {
            if (element == null)
            {
                BH.Engine.Reflection.Compute.RecordWarning(string.Format("Revit element has not been created due to BHoM/Revit conversion issues. BHoM element Guid: {0}", bhomObject.BHoM_Guid));
            }
        }
Beispiel #21
0
        private static ConditionResult VerifyCondition(List <object> objects, HasId idCondition)
        {
            ConditionResult result = new ConditionResult()
            {
                Condition = idCondition
            };

            foreach (var obj in objects)
            {
                IBHoMObject bhomObj = obj as IBHoMObject;

                if (bhomObj == null || idCondition.Ids.Contains(bhomObj.FindFragment <IAdapterId>()?.Id))
                {
                    result.PassedObjects.Add(obj);
                    result.Pattern.Add(true);
                }
                else
                {
                    result.FailedObjects.Add(obj);
                    result.FailInfo.Add($"{(string.IsNullOrWhiteSpace(idCondition.Clause) ? "" : idCondition.Clause + " failed: ")}" +
                                        $"does not have the requested id.");
                    result.Pattern.Add(false);
                }
            }
            return(result);
        }
Beispiel #22
0
        /***************************************************/
        /****              Private methods              ****/
        /***************************************************/

        private static T ElementType <T>(this IBHoMObject bHoMObject, Document document, IEnumerable <BuiltInCategory> builtInCategories = null) where T : ElementType
        {
            string familyName, familyTypeName;

            bHoMObject.FamilyAndTypeNames(out familyName, out familyTypeName);

            return(document.ElementType <T>(familyName, familyTypeName, builtInCategories));
        }
Beispiel #23
0
        /***************************************************/

        private static TestResult TestFailedResult(IBHoMObject obj, string message = "")
        {
            TestResult result = TestResultFromPushedObject(obj);

            result.Message = message;
            result.Status  = oM.Test.TestStatus.Error;
            return(result);
        }
Beispiel #24
0
        /***************************************************/

        private static TestResult TestResultFromPushedObject(IBHoMObject obj)
        {
            return(new TestResult
            {
                Description = $"Test object of type {obj.GetType().Name} with name {obj.Name}",
                ID = obj.Hash(null, true),
            });
        }
Beispiel #25
0
        /***************************************************/
        /****             Interface methods             ****/
        /***************************************************/

        public static bool ISetLocation(this Element element, IBHoMObject bHoMObject, RevitSettings settings)
        {
            if (element == null || bHoMObject == null)
            {
                return(false);
            }

            return(SetLocation(element as dynamic, bHoMObject as dynamic, settings));
        }
Beispiel #26
0
        /***************************************************/
        /**** Public Methods                            ****/
        /***************************************************/

        public static IGeometry IGeometry(this IBHoMObject obj)
        {
            if (obj == null)
            {
                return(null);
            }

            return(Geometry(obj as dynamic));
        }
Beispiel #27
0
        public static string DiffingHash(this IBHoMObject obj, List <string> exceptions = null, bool useDefaultExceptions = true)
        {
            if (exceptions == null || exceptions.Count == 0 && useDefaultExceptions)
            {
                SetDefaultExceptions(ref exceptions);
            }

            return(Compute.SHA256Hash(obj, exceptions));
        }
Beispiel #28
0
        public static RevisionFragment RevisionFragment(this IBHoMObject obj)
        {
            if (obj == null)
            {
                BH.Engine.Reflection.Compute.RecordError("Cannot query the revision fragment from a null object.");
                return(null);
            }

            return(obj.FindFragment <RevisionFragment>());
        }
        /***************************************************/

        internal static void NullRevitElementWarning(this IBHoMObject bhomObject)
        {
            string message = "Referenced Revit element could not be found.";

            if (bhomObject != null)
            {
                message = string.Format("{0} BHoM Guid: {1}", message, bhomObject.BHoM_Guid);
            }

            BH.Engine.Reflection.Compute.RecordWarning(message);
        }
        /***************************************************/

        internal static void ClosedNurbsCurveError(this IBHoMObject iBHoMObject)
        {
            string message = "Revit does not support closed nurbs curves.";

            if (iBHoMObject != null)
            {
                message = string.Format("{0} BHoM Guid: {1}", message, iBHoMObject.BHoM_Guid);
            }

            BH.Engine.Reflection.Compute.RecordWarning(message);
        }